diff --git a/.gitignore b/.gitignore index eee50c47008..b1f5a4205fe 100644 --- a/.gitignore +++ b/.gitignore @@ -299,7 +299,7 @@ package/* generated*/* petstore*/* -**/generated*/* +# **/generated*/* powershell/resources/bin powershell/resources/obj diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase.Data/main.tsp b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase.Data/main.tsp new file mode 100644 index 00000000000..c8cd8e9d1a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase.Data/main.tsp @@ -0,0 +1,59 @@ +import "../LiftrBase/main.tsp"; + +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-resource-manager"; + +using Azure.ResourceManager; +using TypeSpec.Versioning; +using LiftrBase; + +@versioned(LiftrBase.Data.Versions) +namespace LiftrBase.Data; + +@doc("Supported versions for LiftrBase.Data resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1 and LiftrBase.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v1_preview) + v1_preview: "2023-06-01-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1 and LiftrBase.Versions.v2024_08_27_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2024_08_27_preview) + v2024_08_27_preview: "2024-08-27-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1 and LiftrBase.Versions.v2024_08_27") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2024_08_27) + v2024_08_27: "2024-08-27", +} + +@doc("Properties specific to Data Organization resource") +model OrganizationProperties is BaseResourceProperties { + @doc("Organization properties") + partnerOrganizationProperties?: PartnerOrganizationProperties; +} + +@doc("Properties specific to Partner's organization") +model PartnerOrganizationProperties { + @doc("Organization Id in partner's system") + organizationId?: string; + + @doc("Workspace Id in partner's system") + workspaceId?: string; + + @doc("Organization name in partner's system") + @pattern("^[a-zA-Z0-9][a-zA-Z0-9_\\-.: ]*$") + @minLength(1) + @maxLength(50) + organizationName: string; + + @doc("Workspace name in partner's system") + @pattern("^[a-zA-Z0-9][a-zA-Z0-9_\\-.: ]*$") + @minLength(1) + @maxLength(50) + workspaceName?: string; + + @doc("Single Sign On properties for the organization") + singleSignOnProperties?: SingleSignOnProperties; +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase/main.tsp b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase/main.tsp new file mode 100644 index 00000000000..34f517b11ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/LiftrBase/main.tsp @@ -0,0 +1,169 @@ +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/versioning"; + +using Azure.ResourceManager; +using TypeSpec.Versioning; + +@versioned(LiftrBase.Versions) +namespace LiftrBase; + +@doc("Supported versions for LiftrBase resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v1_preview: "2023-06-01-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2024_08_27_preview: "2024-08-27-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v2024_08_27: "2024-08-27", +} + +@doc("Marketplace subscription status of a resource.") +union MarketplaceSubscriptionStatus { + string, + + @doc("Purchased but not yet activated") + PendingFulfillmentStart: "PendingFulfillmentStart", + + @doc("Marketplace subscription is activated") + Subscribed: "Subscribed", + + @doc("This state indicates that a customer's payment for the Marketplace service was not received") + Suspended: "Suspended", + + @doc("Customer has cancelled the subscription") + Unsubscribed: "Unsubscribed", +} + +@added(Versions.v2024_08_27_preview) +@added(Versions.v2024_08_27) +@doc("Subscription renewal mode") +union RenewalMode { + string, + + @doc("Automatic renewal") + Auto: "Auto", + + @doc("Manual renewal") + Manual: "Manual", +} + +@doc("A string that represents a URI.") +scalar Uri extends string; + +@doc("Marketplace details for an organization") +model MarketplaceDetails { + @doc("Azure subscription id for the the marketplace offer is purchased from") + subscriptionId?: string; + + @doc("Marketplace subscription status") + subscriptionStatus?: MarketplaceSubscriptionStatus; + + @doc("Offer details for the marketplace that is selected by the user") + offerDetails: OfferDetails; +} + +@doc("Offer details for the marketplace that is selected by the user") +model OfferDetails { + @doc("Publisher Id for the marketplace offer") + publisherId: string; + + @doc("Offer Id for the marketplace offer") + offerId: string; + + @doc("Plan Id for the marketplace offer") + planId: string; + + @doc("Plan Name for the marketplace offer") + planName?: string; + + @doc("Plan Display Name for the marketplace offer") + termUnit?: string; + + @doc("Plan Display Name for the marketplace offer") + termId?: string; + + @added(Versions.v2024_08_27_preview) + @added(Versions.v2024_08_27) + @doc("Subscription renewal mode") + renewalMode?: RenewalMode; + + @added(Versions.v2024_08_27_preview) + @added(Versions.v2024_08_27) + @doc("Current subscription end date and time") + @visibility("read") + endDate?: utcDateTime; +} + +@doc("Reusable representation of an email address.") +@pattern("^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,}$") +scalar email extends string; + +@doc("User details for an organization") +model UserDetails { + @doc("First name of the user") + firstName: string; + + @doc("Last name of the user") + lastName: string; + + @doc("Email address of the user") + emailAddress: email; + + @doc("User's principal name") + upn?: string; + + @doc("User's phone number") + phoneNumber?: string; +} + +@doc("Base resource properties that can be extended for arm resources.") +model BaseResourceProperties { + @doc("Marketplace details of the resource.") + @visibility("create", "read", "update") + marketplace: MarketplaceDetails; + + @doc("Details of the user.") + user: UserDetails; + + @doc("Provisioning state of the resource.") + @visibility("read") + provisioningState?: ResourceProvisioningState; +} + +@doc("Properties specific to Single Sign On Resource") +model SingleSignOnProperties { + @doc("State of the Single Sign On for the organization") + singleSignOnState?: SingleSignOnStates; + + @doc("AAD enterprise application Id used to setup SSO") + enterpriseAppId?: string; + + @doc("URL for SSO to be used by the partner to redirect the user to their system") + singleSignOnUrl?: Uri; + + @doc("List of AAD domains fetched from Microsoft Graph for user.") + aadDomains?: string[]; + + @visibility("read") + @doc("Provisioning State of the resource") + provisioningState?: ResourceProvisioningState; +} + +@doc("Various states of the SSO resource") +union SingleSignOnStates { + string, + + @doc("Initial state of the SSO resource") + "Initial", + + @doc("State of the SSO resource when it is enabled") + "Enable", + + @doc("State of the SSO resource when it is disabled") + "Disable", +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/client.tsp b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/client.tsp new file mode 100644 index 00000000000..02c6d01bd59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/client.tsp @@ -0,0 +1,6 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(Astronomer.Astro, "AstroMgmt", "python"); diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..47ee80a230f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List - generated by [MaximumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2023-08-01-preview" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "zabhglnki", + "isDataAction": true, + "display": { + "provider": "hgepwsvbptqbigephgxoxyll", + "resource": "thhzqbtxxi", + "operation": "teozafbxkiagahfypii", + "description": "nkucjlsbtriwdgedbxlknbwfz" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "resl" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..9746d08fba7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,180 @@ +{ + "title": "Organizations_CreateOrUpdate - generated by [MaximumSet] rule", + "operationId": "Organizations_CreateOrUpdate", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "resource": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + }, + "201": { + "headers": { + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..e6f1dc6bed0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Delete_MaximumSet_Gen.json @@ -0,0 +1,18 @@ +{ + "title": "Organizations_Delete - generated by [MaximumSet] rule", + "operationId": "Organizations_Delete", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "q:" + }, + "responses": { + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..4cc58a87b3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Get_MaximumSet_Gen.json @@ -0,0 +1,72 @@ +{ + "title": "Organizations_Get - generated by [MaximumSet] rule", + "operationId": "Organizations_Get", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "S PS" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..25dd69bacd8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,76 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MaximumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..017e0ea4bd5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,75 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MaximumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..b8c59d0efa8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01-preview/Organizations_Update_MaximumSet_Gen.json @@ -0,0 +1,122 @@ +{ + "title": "Organizations_Update", + "operationId": "Organizations_Update", + "parameters": { + "api-version": "2023-08-01-preview", + "subscriptionId": "DB5A8803-2521-4C23-B308-7152F9E1A18B", + "resourceGroupName": "rgastronomer", + "organizationName": "6.", + "properties": { + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": { + "key1474": "bqqyipxnbbxryhznyaosmtpo" + }, + "properties": { + "marketplace": { + "subscriptionId": "fpw", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "aboicevbhvmoihqct", + "offerId": "hrwyzmjocfrli", + "planId": "xxscqzzcgp", + "planName": "ewjpobpxhvm", + "termUnit": "tgwvwydtcdldy", + "termId": "guhlhmfyqyguftsjr" + } + }, + "user": { + "firstName": "ndcrxgdwepkowtgxafkhzz", + "lastName": "cnnubonwjtwoaeiewpcmyyggk", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "mpopoqzmcjnofgxxhyzn", + "phoneNumber": "mybpqzaqslyvxm" + }, + "partnerOrganizationProperties": { + "organizationId": "lgfrhysvavtlkdzycmtvf", + "workspaceId": "tzvtdrvn", + "organizationName": "6.", + "workspaceName": "L.-y_--:", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "huxbjdcojsgdpcaehcvzllddhwwcr", + "singleSignOnUrl": "iuxjnaxhuwvla", + "aadDomains": [ + "jmvzsbllhkuch" + ], + "provisioningState": "Succeeded" + } + } + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "fpw", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "aboicevbhvmoihqct", + "offerId": "hrwyzmjocfrli", + "planId": "xxscqzzcgp", + "planName": "ewjpobpxhvm", + "termUnit": "tgwvwydtcdldy", + "termId": "guhlhmfyqyguftsjr" + } + }, + "user": { + "firstName": "ndcrxgdwepkowtgxafkhzz", + "lastName": "cnnubonwjtwoaeiewpcmyyggk", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "mpopoqzmcjnofgxxhyzn", + "phoneNumber": "mybpqzaqslyvxm" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lgfrhysvavtlkdzycmtvf", + "workspaceId": "tzvtdrvn", + "organizationName": "6.", + "workspaceName": "L.-y_--:", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "huxbjdcojsgdpcaehcvzllddhwwcr", + "singleSignOnUrl": "iuxjnaxhuwvla", + "aadDomains": [ + "jmvzsbllhkuch" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "iebkfcpjypgwoxawpyggre", + "id": "fdyntfenvxohkoscvnvdtkxv", + "name": "hstnxzyjtp", + "type": "fpcthygiqzjswaedu", + "systemData": { + "createdBy": "w", + "createdByType": "User", + "createdAt": "2024-09-18T07:31:02.305Z", + "lastModifiedBy": "thgjkgdjdwliegeadwqhevldr", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-09-18T07:31:02.306Z" + } + } + }, + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..ed6f62bf99e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List - generated by [MaximumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2023-08-01" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "zabhglnki", + "isDataAction": true, + "display": { + "provider": "hgepwsvbptqbigephgxoxyll", + "resource": "thhzqbtxxi", + "operation": "teozafbxkiagahfypii", + "description": "nkucjlsbtriwdgedbxlknbwfz" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "resl" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..1fe89dc80cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,180 @@ +{ + "title": "Organizations_CreateOrUpdate - generated by [MaximumSet] rule", + "operationId": "Organizations_CreateOrUpdate", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "resource": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "astronomer1591719760654", + "offerId": "astro", + "planId": "astro-paygo", + "planName": "Monthly Pay-As-You-Go", + "termUnit": "Monthly", + "termId": "gmz7xq9ge3py" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "/subscriptions/6f490d74-8eb4-4e7d-ae07-c75776710bfa/resourceGroups/resourcegroup/providers/Astronomer.Astro/organizations/astro1234", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + }, + "201": { + "headers": { + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..a8c32f20509 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Delete_MaximumSet_Gen.json @@ -0,0 +1,18 @@ +{ + "title": "Organizations_Delete - generated by [MaximumSet] rule", + "operationId": "Organizations_Delete", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "q:" + }, + "responses": { + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..27db2f217a4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Get_MaximumSet_Gen.json @@ -0,0 +1,72 @@ +{ + "title": "Organizations_Get - generated by [MaximumSet] rule", + "operationId": "Organizations_Get", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer", + "organizationName": "S PS" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..6c7829796d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,76 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MaximumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..abc4954a7a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,75 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MaximumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "43454B17-172A-40FE-80FA-549EA23D12B3" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": null, + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "gfsqxygpnerxmvols", + "offerId": "krzkefmpxztqyusidzgpchfaswuyce", + "planId": "kndxzygsanuiqzwbfbbvoipv", + "planName": "pwqjwlq", + "termUnit": "xyygyzcazkuelz", + "termId": "pwds" + } + }, + "user": { + "firstName": "nfh", + "lastName": "lazfbstcccykibvcrxpmglqam", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "xtutvycpxjrtoftx", + "phoneNumber": "inxkscllh" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "lskgzdmziusgrsucv", + "workspaceId": "vcrupxwpaba", + "organizationName": "3-", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "mklfypyujwumgwdzae", + "singleSignOnUrl": "ymmtzkyghvinvhgnqlzwrr", + "aadDomains": [ + "kfbleh" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "mhqthlsatwvqkl", + "id": "bhslekyvgkfomahtvjiin", + "name": "ycyrfvupthkudm", + "type": "ldwwclcpqssjomo", + "systemData": { + "createdBy": "zw", + "createdByType": "User", + "createdAt": "2023-07-25T11:16:12.868Z", + "lastModifiedBy": "isirkhwcppaqoqzoebybzikzbzkjzf", + "lastModifiedByType": "User", + "lastModifiedAt": "2023-07-25T11:16:12.868Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..4b57e965ae8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2023-08-01/Organizations_Update_MaximumSet_Gen.json @@ -0,0 +1,122 @@ +{ + "title": "Organizations_Update", + "operationId": "Organizations_Update", + "parameters": { + "api-version": "2023-08-01", + "subscriptionId": "35FBF232-4B65-40E8-ADA3-49FE99B824D6", + "resourceGroupName": "rgastronomer", + "organizationName": "6.", + "properties": { + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": { + "key1474": "bqqyipxnbbxryhznyaosmtpo" + }, + "properties": { + "marketplace": { + "subscriptionId": "bpoiahcvraqjhwpqcyvmxl", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "zhnlxf", + "offerId": "rh", + "planId": "uqlecfuht", + "planName": "secxe", + "termUnit": "skbmivxsechzkyuxvd", + "termId": "qvnaspsilt" + } + }, + "user": { + "firstName": "pantcaqwknzxnjs", + "lastName": "loytwkjq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "sbfjcucbtwvnnhyzpfycykerzqjvo", + "phoneNumber": "smwcipwxoxdmzgj" + }, + "partnerOrganizationProperties": { + "organizationId": "ugyxg", + "workspaceId": "jbpphzsonkhnaxbwlpmgrwuklcx", + "organizationName": "6.", + "workspaceName": "L.-y_--:", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "hkqosvz", + "singleSignOnUrl": "mgr", + "aadDomains": [ + "ynmjdshvcxpusrtv" + ], + "provisioningState": "Succeeded" + } + } + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "bpoiahcvraqjhwpqcyvmxl", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "zhnlxf", + "offerId": "rh", + "planId": "uqlecfuht", + "planName": "secxe", + "termUnit": "skbmivxsechzkyuxvd", + "termId": "qvnaspsilt" + } + }, + "user": { + "firstName": "pantcaqwknzxnjs", + "lastName": "loytwkjq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "sbfjcucbtwvnnhyzpfycykerzqjvo", + "phoneNumber": "smwcipwxoxdmzgj" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "ugyxg", + "workspaceId": "jbpphzsonkhnaxbwlpmgrwuklcx", + "organizationName": "6.", + "workspaceName": "L.-y_--:", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "hkqosvz", + "singleSignOnUrl": "mgr", + "aadDomains": [ + "ynmjdshvcxpusrtv" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "eyzfomwguzlzdrifqurd", + "id": "bmbatenoclkyauippgw", + "name": "vagudclsnq", + "type": "tjkxdhcixbtpudzrkvlsr", + "systemData": { + "createdBy": "aubmkgdmuh", + "createdByType": "User", + "createdAt": "2024-09-18T09:27:35.952Z", + "lastModifiedBy": "wqcubsxcrhxakigychifzumhtqjtr", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-09-18T09:27:35.953Z" + } + } + }, + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..84610075a9b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List - generated by [MaximumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-08-27-preview" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "unrvqmdvyxlrqgprmwere", + "isDataAction": true, + "display": { + "provider": "bcexjgghgfuudhphysqyvqd", + "resource": "gwrdke", + "operation": "apgxpmzwwphtcj", + "description": "lwsooxrhbrcisbahenmvmkbqpkksuq" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "hupwycy" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MinimumSet_Gen.json new file mode 100644 index 00000000000..42d5fc1ac3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Operations_List_MinimumSet_Gen.json @@ -0,0 +1,12 @@ +{ + "title": "Operations_List - generated by [MinimumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-08-27-preview" + }, + "responses": { + "200": { + "body": {} + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..15397870a96 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,185 @@ +{ + "title": "Organizations_CreateOrUpdate - generated by [MaximumSet] rule", + "operationId": "Organizations_CreateOrUpdate", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "resource": { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:32:38.546Z" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "mialkreryfu", + "name": "lmdyn", + "type": "tzpcxamgfdfxervw", + "systemData": { + "createdBy": "yeyzuhlzka", + "createdByType": "User", + "createdAt": "2024-08-27T06:00:59.057Z", + "lastModifiedBy": "k", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:00:59.057Z" + } + } + }, + "201": { + "headers": { + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:32:38.546Z" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "mialkreryfu", + "name": "lmdyn", + "type": "tzpcxamgfdfxervw", + "systemData": { + "createdBy": "yeyzuhlzka", + "createdByType": "User", + "createdAt": "2024-08-27T06:00:59.057Z", + "lastModifiedBy": "k", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:00:59.057Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..98b713fa267 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Delete_MaximumSet_Gen.json @@ -0,0 +1,18 @@ +{ + "title": "Organizations_Delete - generated by [MaximumSet] rule", + "operationId": "Organizations_Delete", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7" + }, + "responses": { + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..bf3ca784351 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Get_MaximumSet_Gen.json @@ -0,0 +1,74 @@ +{ + "title": "Organizations_Get - generated by [MaximumSet] rule", + "operationId": "Organizations_Get", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:32:38.546Z" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "mialkreryfu", + "name": "lmdyn", + "type": "tzpcxamgfdfxervw", + "systemData": { + "createdBy": "yeyzuhlzka", + "createdByType": "User", + "createdAt": "2024-08-27T06:00:59.057Z", + "lastModifiedBy": "k", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:00:59.057Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..002d7ed8e06 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,78 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MaximumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:32:38.545Z" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "mialkreryfu", + "name": "lmdyn", + "type": "tzpcxamgfdfxervw", + "systemData": { + "createdBy": "yeyzuhlzka", + "createdByType": "User", + "createdAt": "2024-08-27T06:00:59.057Z", + "lastModifiedBy": "k", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:00:59.057Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MinimumSet_Gen.json new file mode 100644 index 00000000000..104e3656930 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListByResourceGroup_MinimumSet_Gen.json @@ -0,0 +1,21 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MinimumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "bhslekyvgkfomahtvjiin" + } + ] + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..76be83eebd3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,77 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MaximumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": "bgvtjtkpxtceyc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "ckrwwvgcfnuzejhmnywtxgtemd", + "offerId": "o", + "planId": "iirdyveiuvufxgnzbggfbnr", + "planName": "lmzofmdkochgzgqzxsuvipuagqizz", + "termUnit": "pzatfjfycsonpuagfzqsz", + "termId": "nrmbsljsrbwsafuwvpa", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:32:38.545Z" + } + }, + "user": { + "firstName": "bvewbyylzjfclpwmozucvjkypq", + "lastName": "nsfq", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ajnhivnhlxebbvbynsoqp", + "phoneNumber": "wincnkeigouajdwhsra" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "suracctmi", + "workspaceId": "yiuanhdcukroyytunueqldcuwtfiwg", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "uv", + "singleSignOnUrl": "zyrtiwivlbtptrszloo", + "aadDomains": [ + "rvyrbq" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "mialkreryfu", + "name": "lmdyn", + "type": "tzpcxamgfdfxervw", + "systemData": { + "createdBy": "yeyzuhlzka", + "createdByType": "User", + "createdAt": "2024-08-27T06:00:59.057Z", + "lastModifiedBy": "k", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:00:59.057Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MinimumSet_Gen.json new file mode 100644 index 00000000000..57ddd6d3276 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_ListBySubscription_MinimumSet_Gen.json @@ -0,0 +1,20 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MinimumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F7135278-5976-4A8C-826F-B0253284766A" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "location": "vyrzuaajyirwimtahombrbsaejcqs", + "id": "bhslekyvgkfomahtvjiin" + } + ] + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..c12d00589d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27-preview/Organizations_Update_MaximumSet_Gen.json @@ -0,0 +1,123 @@ +{ + "title": "Organizations_Update - generated by [MaximumSet] rule", + "operationId": "Organizations_Update", + "parameters": { + "api-version": "2024-08-27-preview", + "subscriptionId": "F87A8461-5F6A-4CE6-8DB2-8BA69C81F2ED", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "properties": { + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "properties": { + "marketplace": { + "subscriptionId": "mxkcsrymflps", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "lottiiwyu", + "offerId": "fesrfmuukwxhopsgsjzmm", + "planId": "edxt", + "planName": "gyzvtm", + "termUnit": "oybzzbnxp", + "termId": "rloaguotiowgrievdwytyjrqou", + "renewalMode": "Auto" + } + }, + "user": { + "firstName": "ddjhcuzarhnieckbbbxacglrl", + "lastName": "xrewtcupqcyrtnenrx", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "uwgltcopuyvpskdtm", + "phoneNumber": "oxtdknmwp" + }, + "partnerOrganizationProperties": { + "organizationId": "uxlyazcd", + "workspaceId": "eofnym", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "dslcwodcitlxknfqgqyjftucfijyt", + "singleSignOnUrl": "vpneskurdmj", + "aadDomains": [ + "fzqllipgsmtwwtbobdhzdcgrkwa" + ], + "provisioningState": "Succeeded" + } + } + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "mxkcsrymflps", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "lottiiwyu", + "offerId": "fesrfmuukwxhopsgsjzmm", + "planId": "edxt", + "planName": "gyzvtm", + "termUnit": "oybzzbnxp", + "termId": "rloaguotiowgrievdwytyjrqou", + "renewalMode": "Auto", + "endDate": "2024-09-18T07:46:35.613Z" + } + }, + "user": { + "firstName": "ddjhcuzarhnieckbbbxacglrl", + "lastName": "xrewtcupqcyrtnenrx", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "uwgltcopuyvpskdtm", + "phoneNumber": "oxtdknmwp" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "uxlyazcd", + "workspaceId": "eofnym", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "dslcwodcitlxknfqgqyjftucfijyt", + "singleSignOnUrl": "vpneskurdmj", + "aadDomains": [ + "fzqllipgsmtwwtbobdhzdcgrkwa" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "hzltyfpyjjcoriwa", + "id": "mwvpxxptqzrydqpbtuzedfuy", + "name": "eidomhauxyovtkno", + "type": "qhpkcbyovjlfco", + "systemData": { + "createdBy": "eodlruyfalpdhlwbnlysmblujs", + "createdByType": "User", + "createdAt": "2024-09-18T07:46:35.614Z", + "lastModifiedBy": "xpuwfqolnygdvfrysxzsfu", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-09-18T07:46:35.614Z" + } + } + }, + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..9c63654be1e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List - generated by [MaximumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-08-27" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "hdagjmhxfewppfmsvhsrdilddtzxrz", + "isDataAction": true, + "display": { + "provider": "klqocuairzcrwxktqfguleptevh", + "resource": "uwlyaybmdmybhyemqwsjcgydg", + "operation": "up", + "description": "ryxgvqwei" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "vm" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MinimumSet_Gen.json new file mode 100644 index 00000000000..2124d145eb8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Operations_List_MinimumSet_Gen.json @@ -0,0 +1,12 @@ +{ + "title": "Operations_List - generated by [MinimumSet] rule", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-08-27" + }, + "responses": { + "200": { + "body": {} + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..f593b66948c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,185 @@ +{ + "title": "Organizations_CreateOrUpdate - generated by [MaximumSet] rule", + "operationId": "Organizations_CreateOrUpdate", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "resource": { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:33:07.745Z" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs", + "id": "ec", + "name": "dfucbeviqfavjryqbflzqttvupne", + "type": "dgccugdynztwzwshuuubefte", + "systemData": { + "createdBy": "daq", + "createdByType": "User", + "createdAt": "2024-08-27T06:02:43.048Z", + "lastModifiedBy": "bewqhprigkbiwlmkmxctd", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:02:43.048Z" + } + } + }, + "201": { + "headers": { + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:33:07.745Z" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs", + "id": "ec", + "name": "dfucbeviqfavjryqbflzqttvupne", + "type": "dgccugdynztwzwshuuubefte", + "systemData": { + "createdBy": "daq", + "createdByType": "User", + "createdAt": "2024-08-27T06:02:43.048Z", + "lastModifiedBy": "bewqhprigkbiwlmkmxctd", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:02:43.048Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..b7c44387f4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Delete_MaximumSet_Gen.json @@ -0,0 +1,18 @@ +{ + "title": "Organizations_Delete - generated by [MaximumSet] rule", + "operationId": "Organizations_Delete", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7" + }, + "responses": { + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..dbcd0c0fc11 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Get_MaximumSet_Gen.json @@ -0,0 +1,74 @@ +{ + "title": "Organizations_Get - generated by [MaximumSet] rule", + "operationId": "Organizations_Get", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:33:07.745Z" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "type": "None", + "userAssignedIdentities": {}, + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2" + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs", + "id": "ec", + "name": "dfucbeviqfavjryqbflzqttvupne", + "type": "dgccugdynztwzwshuuubefte", + "systemData": { + "createdBy": "daq", + "createdByType": "User", + "createdAt": "2024-08-27T06:02:43.048Z", + "lastModifiedBy": "bewqhprigkbiwlmkmxctd", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:02:43.048Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..d5db227b8bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,78 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MaximumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:33:07.743Z" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs", + "id": "ec", + "name": "dfucbeviqfavjryqbflzqttvupne", + "type": "dgccugdynztwzwshuuubefte", + "systemData": { + "createdBy": "daq", + "createdByType": "User", + "createdAt": "2024-08-27T06:02:43.048Z", + "lastModifiedBy": "bewqhprigkbiwlmkmxctd", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:02:43.048Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MinimumSet_Gen.json new file mode 100644 index 00000000000..a24a12e3de2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListByResourceGroup_MinimumSet_Gen.json @@ -0,0 +1,21 @@ +{ + "title": "Organizations_ListByResourceGroup - generated by [MinimumSet] rule", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824", + "resourceGroupName": "rgastronomer" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "location": "pgfkugslgnsxeqpjs", + "id": "bhslekyvgkfomahtvjiin" + } + ] + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..3221367938c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,77 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MaximumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplace": { + "subscriptionId": "emasc", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "kt", + "offerId": "tvidibzbxevtvnrdp", + "planId": "lwcvzdqecwkeracahmixnh", + "planName": "d", + "termUnit": "rs", + "termId": "kopnnjsp", + "renewalMode": "Auto", + "endDate": "2024-09-09T11:33:07.743Z" + } + }, + "user": { + "firstName": "ucowvrccqpqpkdg", + "lastName": "fwwtnwggrtibghoijfzajrhgyo", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "zbdgbbqg", + "phoneNumber": "brnngpezmqecvflklbhsibq" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "juomtfzwkjwnhhpodfnrqdv", + "workspaceId": "nnryjcmiohmkbvhngfgxigpodvhl", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "srkwxktx", + "singleSignOnUrl": "l", + "aadDomains": [ + "fcnqoizqxcdclmy" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "pgfkugslgnsxeqpjs", + "id": "ec", + "name": "dfucbeviqfavjryqbflzqttvupne", + "type": "dgccugdynztwzwshuuubefte", + "systemData": { + "createdBy": "daq", + "createdByType": "User", + "createdAt": "2024-08-27T06:02:43.048Z", + "lastModifiedBy": "bewqhprigkbiwlmkmxctd", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-08-27T06:02:43.048Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MinimumSet_Gen.json new file mode 100644 index 00000000000..a7271c29873 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_ListBySubscription_MinimumSet_Gen.json @@ -0,0 +1,20 @@ +{ + "title": "Organizations_ListBySubscription - generated by [MinimumSet] rule", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "A4679760-5C37-44EA-A4B8-8A7628B13824" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "location": "pgfkugslgnsxeqpjs", + "id": "bhslekyvgkfomahtvjiin" + } + ] + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..9b2a104e359 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/examples/2024-08-27/Organizations_Update_MaximumSet_Gen.json @@ -0,0 +1,123 @@ +{ + "title": "Organizations_Update - generated by [MaximumSet] rule", + "operationId": "Organizations_Update", + "parameters": { + "api-version": "2024-08-27", + "subscriptionId": "ECBF1ABA-FCBB-46A5-BFC3-3334D65EC8F7", + "resourceGroupName": "rgastronomer", + "organizationName": "U.1-:7", + "properties": { + "identity": { + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "properties": { + "marketplace": { + "subscriptionId": "ujl", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "bywzycdrucjkx", + "offerId": "aljpaprqzpnivwol", + "planId": "fcpnstrwetlrajanh", + "planName": "wjgnlhqqkdi", + "termUnit": "pvpk", + "termId": "xg", + "renewalMode": "Auto" + } + }, + "user": { + "firstName": "wyoaxocyjfpgicvketuiayfxrxq", + "lastName": "vlwybhfayupjpwfhy", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ezefcwbsbgcxrdiixmzphibt", + "phoneNumber": "eibhsslqzufgshuzrjjyymsb" + }, + "partnerOrganizationProperties": { + "organizationId": "linzwcqhrpqrxpnghxjnxzetfdps", + "workspaceId": "tmmxzlagmdrc", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "jspfkoxolosmvyixpktbwyoqrx", + "singleSignOnUrl": "aatouxlmqqizijszlu", + "aadDomains": [ + "gwzhrfmnhbeitagjdlzw" + ], + "provisioningState": "Succeeded" + } + } + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplace": { + "subscriptionId": "ujl", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "bywzycdrucjkx", + "offerId": "aljpaprqzpnivwol", + "planId": "fcpnstrwetlrajanh", + "planName": "wjgnlhqqkdi", + "termUnit": "pvpk", + "termId": "xg", + "renewalMode": "Auto", + "endDate": "2024-09-18T09:36:40.774Z" + } + }, + "user": { + "firstName": "wyoaxocyjfpgicvketuiayfxrxq", + "lastName": "vlwybhfayupjpwfhy", + "emailAddress": ".K_@e7N-g1.xjqnbPs", + "upn": "ezefcwbsbgcxrdiixmzphibt", + "phoneNumber": "eibhsslqzufgshuzrjjyymsb" + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "linzwcqhrpqrxpnghxjnxzetfdps", + "workspaceId": "tmmxzlagmdrc", + "organizationName": "U.1-:7", + "workspaceName": "9.:06", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "jspfkoxolosmvyixpktbwyoqrx", + "singleSignOnUrl": "aatouxlmqqizijszlu", + "aadDomains": [ + "gwzhrfmnhbeitagjdlzw" + ], + "provisioningState": "Succeeded" + } + } + }, + "identity": { + "principalId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "tenantId": "b5684bd7-7958-4c0e-9795-d686c31746d2", + "type": "None", + "userAssignedIdentities": {} + }, + "tags": {}, + "location": "lpfjmjgqgqiecnek", + "id": "dxlysdjielachwxeyxqwnjxehwda", + "name": "fystkqkhbfxuotqxhft", + "type": "bipflhqhapjtuiknj", + "systemData": { + "createdBy": "ldetdeujxj", + "createdByType": "User", + "createdAt": "2024-09-18T09:36:40.776Z", + "lastModifiedBy": "hfwzlknbcscvxdr", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-09-18T09:36:40.776Z" + } + } + }, + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/main.tsp b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/main.tsp new file mode 100644 index 00000000000..2c2da6856c6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/main.tsp @@ -0,0 +1,84 @@ +import "./LiftrBase.Data/main.tsp"; + +import "@typespec/rest"; +import "@typespec/versioning"; +import "@azure-tools/typespec-autorest"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Versioning; +using LiftrBase.Data; + +@armProviderNamespace +@service({ + title: "Astronomer.Astro", +}) +@versioned(Astronomer.Astro.Versions) +namespace Astronomer.Astro; + +@doc("Supported API versions for the Astronomer.Astro resource provider.") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1, LiftrBase.Versions.v1_preview, LiftrBase.Data.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v1_preview) + @useDependency(LiftrBase.Data.Versions.v1_preview) + v1_preview: "2023-08-01-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1, LiftrBase.Versions.v1_preview, LiftrBase.Data.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v1_preview) + @useDependency(LiftrBase.Data.Versions.v1_preview) + v1: "2023-08-01", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1, LiftrBase.Versions.v2024_08_27_preview, LiftrBase.Data.Versions.v2024_08_27_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2024_08_27_preview) + @useDependency(LiftrBase.Data.Versions.v2024_08_27_preview) + v2024_08_27_preview: "2024-08-27-preview", + + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1, LiftrBase.Versions.v2024_08_27, LiftrBase.Data.Versions.v2024_08_27") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2024_08_27) + @useDependency(LiftrBase.Data.Versions.v2024_08_27) + v2024_08_27: "2024-08-27", +} + +interface Operations extends Azure.ResourceManager.Operations {} + +@doc("Organization Resource by Astronomer") +model OrganizationResource is TrackedResource { + @key("organizationName") + @pattern("^[a-zA-Z0-9][a-zA-Z0-9_\\-.: ]*$") + @segment("organizations") + @minLength(1) + @maxLength(50) + @doc("Name of the Organizations resource") + @path + name: string; + + ...Legacy.ManagedServiceIdentityV4Property; +} + +@armResourceOperations +interface Organizations { + get is ArmResourceRead; + #suppress "@azure-tools/typespec-azure-core/invalid-final-state" "MUST CHANGE ON NEXT UPDATE" + @Azure.Core.useFinalStateVia("azure-async-operation") + createOrUpdate is ArmResourceCreateOrUpdateAsync< + OrganizationResource, + LroHeaders = Azure.Core.Foundations.RetryAfterHeader + >; + update is ArmCustomPatchAsync< + OrganizationResource, + Azure.ResourceManager.Foundations.ResourceUpdateModel< + OrganizationResource, + OrganizationProperties + > + >; + delete is ArmResourceDeleteWithoutOkAsync; + listByResourceGroup is ArmResourceListByParent; + listBySubscription is ArmListBySubscription; +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/.gitattributes b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.csproj b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.csproj new file mode 100644 index 00000000000..a9a2158318b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.Astro.private + false + Microsoft.Azure.PowerShell.Cmdlets.Astro + true + false + ./bin + $(OutputPath) + Az.Astro.nuspec + true + + + 1998, 1591 + true + + + + false + TRACE;DEBUG;NETSTANDARD + + + + true + true + MSSharedLibKey.snk + TRACE;RELEASE;NETSTANDARD;SIGN + + + + + + + + + $(DefaultItemExcludes);resources/** + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.nuspec b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.nuspec new file mode 100644 index 00000000000..1c768281e7d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.nuspec @@ -0,0 +1,32 @@ + + + + Az.Astro + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: Astro cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Sphere + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.psm1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.psm1 new file mode 100644 index 00000000000..720b85bf926 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/Az.Astro.psm1 @@ -0,0 +1,119 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.Astro.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Astro.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/README.md new file mode 100644 index 00000000000..ef329cd90e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/README.md @@ -0,0 +1,24 @@ + +# Az.Astro +This directory contains the PowerShell module for the Astro service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Astro`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/build-module.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/build-module.ps1 new file mode 100644 index 00000000000..ad86127f262 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $NotIsolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +$isAzure = [System.Convert]::ToBoolean('true') + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Astro.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.Astro.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.Astro.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.Astro' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: Astro cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.Astro.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and ((-not (Test-Path -Path $resourceModule)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..f48ae1671ea --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if (''.length -gt 0) { + $ModuleName = '' + } else { + $ModuleName = 'Az.Astro' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('Astro')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'Astro' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/Az.Astro.custom.psm1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/Az.Astro.custom.psm1 new file mode 100644 index 00000000000..ecef648375a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/Az.Astro.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Astro.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/README.md new file mode 100644 index 00000000000..ac4ee062da4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.Astro` 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.Astro.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.Astro` 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.Astro.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.Astro.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.Astro`. 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.Astro.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.Astro.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.Astro`. +- `Microsoft.Azure.PowerShell.Cmdlets.Astro.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.Astro`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/docs/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/docs/README.md new file mode 100644 index 00000000000..f00b6fdf82f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Astro` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Astro` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/examples/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/export-surface.ps1 new file mode 100644 index 00000000000..39daed709df --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Astro.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.Astro' +$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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/exports/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/exports/README.md new file mode 100644 index 00000000000..f891d78078f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.Astro`. No other cmdlets in this repository are directly exported. What that means is the `Az.Astro` module will run [Export-ModuleMember](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.Astro.private.dll`) and from the `..\custom\Az.Astro.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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-help.ps1 new file mode 100644 index 00000000000..7edcf500b41 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Astro.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.Astro.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Astro.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..a7f1615ed2e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generate-portal-ux.ps1 @@ -0,0 +1,383 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.Astro' +$rootModuleName = '' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Astro.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + if ($Null -eq $example) + { + $example = @() + } + + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + if ($Null -eq $signature) + { + $signature = @() + } + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/Module.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/Module.cs new file mode 100644 index 00000000000..f6fc5e3f6e5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/Module.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.Astro.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + public bool _useProxy = false; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.Astro"; + + /// 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.Astro"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_useProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/AstronomerAstro.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/AstronomerAstro.cs new file mode 100644 index 00000000000..eb5ff0a2dc5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/AstronomerAstro.cs @@ -0,0 +1,2771 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Low-level API implementation for the Astronomer.Astro service. + /// + public partial class AstronomerAstro + { + + /// List the operations for the 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.Astro.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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Astronomer.Astro/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the 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.Astro.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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Astronomer.Astro/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Astronomer.Astro/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Astronomer.Astro/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the provider + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Astronomer.Astro/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Astronomer.Astro/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Astronomer.Astro/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// List the operations for the provider + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListWithResult(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Astronomer.Astro/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Resource create parameters. + /// 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.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// Resource create parameters. + /// 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.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Json string supplied to the OrganizationsCreateOrUpdate operation + /// 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.Astro.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 OrganizationsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Json string supplied to the OrganizationsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Astro.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Astro.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Astro.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsCreateOrUpdate_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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Astro.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Astro.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Astro.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Resource create parameters. + /// 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 OrganizationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.Astro.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Astro.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 OrganizationsDelete(string subscriptionId, string resourceGroupName, string organizationName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a OrganizationResource + /// + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Astro.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 OrganizationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Astro.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 OrganizationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Astro.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Astro.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Astro.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations 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 OrganizationsDelete_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + } + } + + /// Get a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations 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.Astro.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 OrganizationsGet(string subscriptionId, string resourceGroupName, string organizationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a OrganizationResource + /// + /// 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.Astro.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 OrganizationsGetViaIdentity(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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a OrganizationResource + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsGetWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsGet_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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations 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 OrganizationsGet_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + } + } + + /// List OrganizationResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// 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.Astro.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 OrganizationsListByResourceGroup(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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by 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.Astro.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 OrganizationsListByResourceGroupViaIdentity(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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations$", 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/Astronomer.Astro/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by resource group + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations$", 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/Astronomer.Astro/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// List OrganizationResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListByResourceGroup_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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// 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 OrganizationsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Astro.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\._\(\)]+$"); + } + } + + /// List OrganizationResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// 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.Astro.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 OrganizationsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// + /// 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.Astro.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 OrganizationsListBySubscriptionViaIdentity(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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Astronomer.Astro/organizations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Astronomer.Astro/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Astronomer.Astro/organizations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Astronomer.Astro/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Astronomer.Astro/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsListBySubscription_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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// 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 OrganizationsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// The resource properties to be updated. + /// 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.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a OrganizationResource + /// + /// The resource properties to be updated. + /// 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.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a OrganizationResource + /// + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // 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/Astronomer.Astro/organizations/(?[^/]+)$", 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/Astronomer.Astro/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Astronomer.Astro/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Json string supplied to the OrganizationsUpdate operation + /// 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.Astro.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 OrganizationsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// Json string supplied to the OrganizationsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-27"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Astronomer.Astro/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Astro.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Astro.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Astro.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Astro.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 OrganizationsUpdate_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.Astro.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Astro.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Astro.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Astro.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Organizations resource + /// The resource properties to be updated. + /// 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 OrganizationsUpdate_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Astro.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..044ab4efc07 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.PowerShell.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial class Any + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Any(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Any(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Any(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Any(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial interface IAny + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..b5920ccd543 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Any.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Any.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..170eec31928 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..19c85a0507d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Any.json.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Anything + public partial class Any + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new Any(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.PowerShell.cs new file mode 100644 index 00000000000..412f1f74554 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.PowerShell.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(AstroIdentityTypeConverter))] + public partial class AstroIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AstroIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)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 AstroIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal)this).Id, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AstroIdentity(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.Astro.Models.IAstroIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AstroIdentity(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.Astro.Models.IAstroIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(AstroIdentityTypeConverter))] + public partial interface IAstroIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.TypeConverter.cs new file mode 100644 index 00000000000..9f42a77bb34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.TypeConverter.cs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AstroIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity 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 AstroIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AstroIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AstroIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AstroIdentity.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.cs new file mode 100644 index 00000000000..8728d37e118 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class AstroIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentityInternal + { + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _organizationName; + + /// Name of the Organizations resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string OrganizationName { get => this._organizationName; set => this._organizationName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public AstroIdentity() + { + + } + } + public partial interface IAstroIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Name of the Organizations resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string OrganizationName { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + 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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IAstroIdentityInternal + + { + /// Resource identity path + string Id { get; set; } + /// Name of the Organizations resource + string OrganizationName { get; set; } + /// The name of the resource group. The name is case insensitive. + string ResourceGroupName { get; set; } + /// The ID of the target subscription. The value must be an UUID. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.json.cs new file mode 100644 index 00000000000..fd39f1c6c92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/AstroIdentity.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class AstroIdentity + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal AstroIdentity(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)_resourceGroupName;} + {_organizationName = If( json?.PropertyT("organizationName"), out var __jsonOrganizationName) ? (string)__jsonOrganizationName : (string)_organizationName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new AstroIdentity(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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._organizationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._organizationName.ToString()) : null, "organizationName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..2914e7f9c5f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial class ErrorAdditionalInfo + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorAdditionalInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorAdditionalInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial interface IErrorAdditionalInfo + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..1941a8dcb2c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorAdditionalInfoTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorAdditionalInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..3c1afee9dbc --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorAdditionalInfo() + { + + } + } + /// The resource management error additional info. + public partial interface IErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info.", + SerializedName = @"info", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource management error additional info. + internal partial interface IErrorAdditionalInfoInternal + + { + /// The additional info. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAny Info { get; set; } + /// The additional info type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..b3aa20212f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorAdditionalInfo.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_info = If( json?.PropertyT("info"), out var __jsonInfo) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new ErrorAdditionalInfo(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._info.ToJson(null,serializationMode) : null, "info" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..9384a14b86c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial class ErrorDetail + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetail(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetail(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial interface IErrorDetail + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..83c9c17fd4d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetail.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..01102401620 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public System.Collections.Generic.List AdditionalInfo { get => this._additionalInfo; } + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Creates an new instance. + public ErrorDetail() + { + + } + } + /// The error detail. + public partial interface IErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// The error detail. + internal partial interface IErrorDetailInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..809680e72af --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorDetail.json.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new ErrorDetail(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.XNodeArray(); + foreach( var __s in this._additionalInfo ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("additionalInfo",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..899be6aeb49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial class ErrorResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Target, 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 + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal)this).Target, 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.Astro.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..cdfa6289729 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..5520329089c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).AdditionalInfo = value; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Code = value; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Message = value; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Target = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + internal partial interface IErrorResponseInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..7df22f89670 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ErrorResponse.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.PowerShell.cs new file mode 100644 index 00000000000..0f764b377ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Managed service identity (system assigned and/or user assigned identities) + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityV4TypeConverter))] + public partial class ManagedServiceIdentityV4 + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentityV4(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.Astro.Models.IManagedServiceIdentityV4 DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentityV4(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.Astro.Models.IManagedServiceIdentityV4 FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentityV4(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedServiceIdentityV4(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Managed service identity (system assigned and/or user assigned identities) + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityV4TypeConverter))] + public partial interface IManagedServiceIdentityV4 + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.TypeConverter.cs new file mode 100644 index 00000000000..dd84b1ab86c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityV4TypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentityV4.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentityV4.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentityV4.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.cs new file mode 100644 index 00000000000..b5de6ed1dcb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentityV4 : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Backing field for property. + private string _type; + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentities()); set => this._userAssignedIdentity = value; } + + /// Creates an new instance. + public ManagedServiceIdentityV4() + { + + } + } + /// Managed service identity (system assigned and/or user assigned identities) + public partial interface IManagedServiceIdentityV4 : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities UserAssignedIdentity { get; set; } + + } + /// Managed service identity (system assigned and/or user assigned identities) + internal partial interface IManagedServiceIdentityV4Internal + + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string PrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string TenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.json.cs new file mode 100644 index 00000000000..c44ee124c66 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/ManagedServiceIdentityV4.json.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentityV4 + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new ManagedServiceIdentityV4(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentityV4(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)_principalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)_tenantId;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_userAssignedIdentity = If( json?.PropertyT("userAssignedIdentities"), out var __jsonUserAssignedIdentities) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentities.FromJson(__jsonUserAssignedIdentities) : _userAssignedIdentity;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._userAssignedIdentity.ToJson(null,serializationMode) : null, "userAssignedIdentities" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs new file mode 100644 index 00000000000..dd071891bfe --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Marketplace details for an organization + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial class MarketplaceDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MarketplaceDetails(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.Astro.Models.IMarketplaceDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MarketplaceDetails(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.Astro.Models.IMarketplaceDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MarketplaceDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("OfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("OfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus = (string) content.GetValueForProperty("SubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailEndDate, (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 MarketplaceDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("OfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("OfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus = (string) content.GetValueForProperty("SubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)this).OfferDetailEndDate, (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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Marketplace details for an organization + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial interface IMarketplaceDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs new file mode 100644 index 00000000000..7e9223fac29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MarketplaceDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MarketplaceDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MarketplaceDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MarketplaceDetails.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.cs new file mode 100644 index 00000000000..ffdbd2c25c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.cs @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Marketplace details for an organization + public partial class MarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal + { + + /// Internal Acessors for OfferDetail + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal.OfferDetail { get => (this._offerDetail = this._offerDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetails()); set { {_offerDetail = value;} } } + + /// Internal Acessors for OfferDetailEndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal.OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).EndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).EndDate = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails _offerDetail; + + /// Offer details for the marketplace that is selected by the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails OfferDetail { get => (this._offerDetail = this._offerDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetails()); set => this._offerDetail = value; } + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).EndDate; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).OfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).OfferId = value ; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PlanId = value ; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).PublisherId = value ; } + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailRenewalMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).RenewalMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).RenewalMode = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).TermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).TermId = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)OfferDetail).TermUnit = value ?? null; } + + /// Backing field for property. + private string _subscriptionId; + + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _subscriptionStatus; + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string SubscriptionStatus { get => this._subscriptionStatus; set => this._subscriptionStatus = value; } + + /// Creates an new instance. + public MarketplaceDetails() + { + + } + } + /// Marketplace details for an organization + public partial interface IMarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? OfferDetailEndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string SubscriptionStatus { get; set; } + + } + /// Marketplace details for an organization + internal partial interface IMarketplaceDetailsInternal + + { + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails OfferDetail { get; set; } + /// Current subscription end date and time + global::System.DateTime? OfferDetailEndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + string SubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string SubscriptionStatus { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.json.cs new file mode 100644 index 00000000000..c199b1656cd --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/MarketplaceDetails.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Marketplace details for an organization + public partial class MarketplaceDetails + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new MarketplaceDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal MarketplaceDetails(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_offerDetail = If( json?.PropertyT("offerDetails"), out var __jsonOfferDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetails.FromJson(__jsonOfferDetails) : _offerDetail;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_subscriptionStatus = If( json?.PropertyT("subscriptionStatus"), out var __jsonSubscriptionStatus) ? (string)__jsonSubscriptionStatus : (string)_subscriptionStatus;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._offerDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._offerDetail.ToJson(null,serializationMode) : null, "offerDetails" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._subscriptionStatus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._subscriptionStatus.ToString()) : null, "subscriptionStatus" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.PowerShell.cs new file mode 100644 index 00000000000..8b95c456f58 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.PowerShell.cs @@ -0,0 +1,218 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Offer details for the marketplace that is selected by the user + [System.ComponentModel.TypeConverter(typeof(OfferDetailsTypeConverter))] + public partial class OfferDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OfferDetails(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.Astro.Models.IOfferDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OfferDetails(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.Astro.Models.IOfferDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OfferDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("PlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanName, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermId = (string) content.GetValueForProperty("TermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermId, global::System.Convert.ToString); + } + if (content.Contains("RenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).RenewalMode = (string) content.GetValueForProperty("RenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).RenewalMode, global::System.Convert.ToString); + } + if (content.Contains("EndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).EndDate = (global::System.DateTime?) content.GetValueForProperty("EndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).EndDate, (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 OfferDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("PlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).PlanName, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermId = (string) content.GetValueForProperty("TermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).TermId, global::System.Convert.ToString); + } + if (content.Contains("RenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).RenewalMode = (string) content.GetValueForProperty("RenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).RenewalMode, global::System.Convert.ToString); + } + if (content.Contains("EndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).EndDate = (global::System.DateTime?) content.GetValueForProperty("EndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal)this).EndDate, (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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Offer details for the marketplace that is selected by the user + [System.ComponentModel.TypeConverter(typeof(OfferDetailsTypeConverter))] + public partial interface IOfferDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs new file mode 100644 index 00000000000..858ff4944ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OfferDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OfferDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OfferDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OfferDetails.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.cs new file mode 100644 index 00000000000..c232c50e96b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Offer details for the marketplace that is selected by the user + public partial class OfferDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal + { + + /// Backing field for property. + private global::System.DateTime? _endDate; + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public global::System.DateTime? EndDate { get => this._endDate; } + + /// Internal Acessors for EndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetailsInternal.EndDate { get => this._endDate; set { {_endDate = value;} } } + + /// Backing field for property. + private string _offerId; + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string OfferId { get => this._offerId; set => this._offerId = value; } + + /// Backing field for property. + private string _planId; + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PlanId { get => this._planId; set => this._planId = value; } + + /// Backing field for property. + private string _planName; + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PlanName { get => this._planName; set => this._planName = value; } + + /// Backing field for property. + private string _publisherId; + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PublisherId { get => this._publisherId; set => this._publisherId = value; } + + /// Backing field for property. + private string _renewalMode; + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string RenewalMode { get => this._renewalMode; set => this._renewalMode = value; } + + /// Backing field for property. + private string _termId; + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string TermId { get => this._termId; set => this._termId = value; } + + /// Backing field for property. + private string _termUnit; + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string TermUnit { get => this._termUnit; set => this._termUnit = value; } + + /// Creates an new instance. + public OfferDetails() + { + + } + } + /// Offer details for the marketplace that is selected by the user + public partial interface IOfferDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string PlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string PlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string PublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string RenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string TermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// Offer details for the marketplace that is selected by the user + internal partial interface IOfferDetailsInternal + + { + /// Current subscription end date and time + global::System.DateTime? EndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferId { get; set; } + /// Plan Id for the marketplace offer + string PlanId { get; set; } + /// Plan Name for the marketplace offer + string PlanName { get; set; } + /// Publisher Id for the marketplace offer + string PublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string RenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string TermId { get; set; } + /// Plan Display Name for the marketplace offer + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.json.cs new file mode 100644 index 00000000000..4b200758626 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OfferDetails.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Offer details for the marketplace that is selected by the user + public partial class OfferDetails + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OfferDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OfferDetails(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_publisherId = If( json?.PropertyT("publisherId"), out var __jsonPublisherId) ? (string)__jsonPublisherId : (string)_publisherId;} + {_offerId = If( json?.PropertyT("offerId"), out var __jsonOfferId) ? (string)__jsonOfferId : (string)_offerId;} + {_planId = If( json?.PropertyT("planId"), out var __jsonPlanId) ? (string)__jsonPlanId : (string)_planId;} + {_planName = If( json?.PropertyT("planName"), out var __jsonPlanName) ? (string)__jsonPlanName : (string)_planName;} + {_termUnit = If( json?.PropertyT("termUnit"), out var __jsonTermUnit) ? (string)__jsonTermUnit : (string)_termUnit;} + {_termId = If( json?.PropertyT("termId"), out var __jsonTermId) ? (string)__jsonTermId : (string)_termId;} + {_renewalMode = If( json?.PropertyT("renewalMode"), out var __jsonRenewalMode) ? (string)__jsonRenewalMode : (string)_renewalMode;} + {_endDate = If( json?.PropertyT("endDate"), out var __jsonEndDate) ? global::System.DateTime.TryParse((string)__jsonEndDate, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEndDateValue) ? __jsonEndDateValue : _endDate : _endDate;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._publisherId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._publisherId.ToString()) : null, "publisherId" ,container.Add ); + AddIf( null != (((object)this._offerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._offerId.ToString()) : null, "offerId" ,container.Add ); + AddIf( null != (((object)this._planId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._planId.ToString()) : null, "planId" ,container.Add ); + AddIf( null != (((object)this._planName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._planName.ToString()) : null, "planName" ,container.Add ); + AddIf( null != (((object)this._termUnit)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._termUnit.ToString()) : null, "termUnit" ,container.Add ); + AddIf( null != (((object)this._termId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._termId.ToString()) : null, "termId" ,container.Add ); + AddIf( null != (((object)this._renewalMode)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._renewalMode.ToString()) : null, "renewalMode" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._endDate ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._endDate?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "endDate" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..8a9754f6e94 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.PowerShell.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial class Operation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Operation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Operation(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Operation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..c26172dc91c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Operation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Operation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..7a8d401ef0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal + { + + /// Backing field for property. + private string _actionType; + + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; set => this._actionType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationDisplay()); } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Description; } + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Operation; } + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Provider; } + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Resource; } + + /// Backing field for property. + private bool? _isDataAction; + + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Extensible enum. Indicates the action type. ""Internal"" refers to actions that are for internal only APIs.", + SerializedName = @"actionType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Whether the operation applies to data-plane. This is ""true"" for data-plane operations and ""false"" for Azure Resource Manager/control-plane operations.", + SerializedName = @"isDataAction", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDataAction { get; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the operation, as per Resource-Based Access Control (RBAC). Examples: ""Microsoft.Compute/virtualMachines/write"", ""Microsoft.Compute/virtualMachines/capture/action""", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is ""user,system""", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; } + + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + internal partial interface IOperationInternal + + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay Display { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string DisplayOperation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string DisplayResource { get; set; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + bool? IsDataAction { get; set; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + string Name { get; set; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..1a2d8640a32 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Operation.json.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Models.OperationDisplay.FromJson(__jsonDisplay) : _display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_isDataAction = If( json?.PropertyT("isDataAction"), out var __jsonIsDataAction) ? (bool?)__jsonIsDataAction : _isDataAction;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)_origin;} + {_actionType = If( json?.PropertyT("actionType"), out var __jsonActionType) ? (string)__jsonActionType : (string)_actionType;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._actionType.ToString()) : null, "actionType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..5f262150165 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial class OperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDisplay(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDisplay(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..285b9db9192 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..f151878101a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Localized display information for and operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Localized display information for and operation. + internal partial interface IOperationDisplayInternal + + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string Description { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string Operation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string Provider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..594dfe5eed5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationDisplay.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Localized display information for and 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)_provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)_resource;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)_operation;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..d028f1369bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial class OperationListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..797962c8e41 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..08d1a240558 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Operation items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation) })] + System.Collections.Generic.List Value { get; set; } + + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + internal partial interface IOperationListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Operation items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..be41e7764ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OperationListResult.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Operation.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.PowerShell.cs new file mode 100644 index 00000000000..3da114bd6f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.PowerShell.cs @@ -0,0 +1,394 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Properties specific to Data Organization resource + [System.ComponentModel.TypeConverter(typeof(OrganizationPropertiesTypeConverter))] + public partial class OrganizationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationProperties(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.Astro.Models.IOrganizationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationProperties(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.Astro.Models.IOrganizationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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 OrganizationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Data Organization resource + [System.ComponentModel.TypeConverter(typeof(OrganizationPropertiesTypeConverter))] + public partial interface IOrganizationProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs new file mode 100644 index 00000000000..561f2b8050a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationProperties.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.cs new file mode 100644 index 00000000000..366375d6657 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.cs @@ -0,0 +1,525 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Data Organization resource + public partial class OrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails _marketplace; + + /// Marketplace details of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get => (this._marketplace = this._marketplace ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails()); set => this._marketplace = value; } + + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionStatus = value ?? null; } + + /// Internal Acessors for Marketplace + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.Marketplace { get => (this._marketplace = this._marketplace ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails()); set { {_marketplace = value;} } } + + /// Internal Acessors for MarketplaceOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.MarketplaceOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetail = value; } + + /// Internal Acessors for OfferDetailEndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties()); set { {_partnerOrganizationProperty = value;} } } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for SingleSignOnPropertyProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState = value; } + + /// Internal Acessors for User + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal.User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails()); set { {_user = value;} } } + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailOfferId = value ; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanId = value ; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPublisherId = value ; } + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailRenewalMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailRenewalMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailRenewalMode = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermId = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermUnit = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties _partnerOrganizationProperty; + + /// Organization properties + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties()); set => this._partnerOrganizationProperty = value; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName = value ?? null; } + + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceId = value ?? null; } + + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceName = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails _user; + + /// Details of the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails()); set => this._user = value; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).EmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).EmailAddress = value ; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).FirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).FirstName = value ; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).LastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).LastName = value ; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).PhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).PhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).Upn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).Upn = value ?? null; } + + /// Creates an new instance. + public OrganizationProperties() + { + + } + } + /// Properties specific to Data Organization resource + public partial interface IOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? OfferDetailEndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning state of the resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserUpn { get; set; } + + } + /// Properties specific to Data Organization resource + internal partial interface IOrganizationPropertiesInternal + + { + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails MarketplaceOfferDetail { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + global::System.DateTime? OfferDetailEndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// Workspace Id in partner's system + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get; set; } + /// Email address of the user + string UserEmailAddress { get; set; } + /// First name of the user + string UserFirstName { get; set; } + /// Last name of the user + string UserLastName { get; set; } + /// User's phone number + string UserPhoneNumber { get; set; } + /// User's principal name + string UserUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.json.cs new file mode 100644 index 00000000000..5360874253d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Data Organization resource + public partial class OrganizationProperties + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationProperties(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplace = If( json?.PropertyT("marketplace"), out var __jsonMarketplace) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails.FromJson(__jsonMarketplace) : _marketplace;} + {_user = If( json?.PropertyT("user"), out var __jsonUser) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails.FromJson(__jsonUser) : _user;} + {_partnerOrganizationProperty = If( json?.PropertyT("partnerOrganizationProperties"), out var __jsonPartnerOrganizationProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties.FromJson(__jsonPartnerOrganizationProperties) : _partnerOrganizationProperty;} + {_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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._marketplace ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._marketplace.ToJson(null,serializationMode) : null, "marketplace" ,container.Add ); + AddIf( null != this._user ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._user.ToJson(null,serializationMode) : null, "user" ,container.Add ); + AddIf( null != this._partnerOrganizationProperty ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._partnerOrganizationProperty.ToJson(null,serializationMode) : null, "partnerOrganizationProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs new file mode 100644 index 00000000000..1d10323bafe --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs @@ -0,0 +1,546 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Organization Resource by Astronomer + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceTypeConverter))] + public partial class OrganizationResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResource(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.Astro.Models.IOrganizationResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResource(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.Astro.Models.IOrganizationResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4TypeConverter.ConvertFrom); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyProvisioningState, 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 OrganizationResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4TypeConverter.ConvertFrom); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Organization Resource by Astronomer + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceTypeConverter))] + public partial interface IOrganizationResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs new file mode 100644 index 00000000000..4fcf0330254 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResource.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.cs new file mode 100644 index 00000000000..765ef1df376 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.cs @@ -0,0 +1,730 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Organization Resource by Astronomer + public partial class OrganizationResource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IValidates, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TrackedResource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4()); set => this._identity = value; } + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId; } + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)__trackedResource).Location = value ; } + + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceSubscriptionStatus = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId = value; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId = value; } + + /// Internal Acessors for Marketplace + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.Marketplace { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).Marketplace; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).Marketplace = value; } + + /// Internal Acessors for MarketplaceOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.MarketplaceOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceOfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).MarketplaceOfferDetail = value; } + + /// Internal Acessors for OfferDetailEndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailEndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailEndDate = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.PartnerOrganizationProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationProperty = value; } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for SingleSignOnPropertyProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyProvisioningState = value; } + + /// Internal Acessors for User + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal.User { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).User; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).User = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Name; } + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailEndDate; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailOfferId = value ?? null; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanId = value ?? null; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailPublisherId = value ?? null; } + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailRenewalMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailRenewalMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailRenewalMode = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermId = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermUnit = value ?? null; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName = value ?? null; } + + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceId = value ?? null; } + + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceName = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyProvisioningState; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)__trackedResource).Tag = value ?? null /* model class */; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__trackedResource).Type; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserEmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserEmailAddress = value ?? null; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserFirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserFirstName = value ?? null; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserLastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserLastName = value ?? null; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserPhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserPhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserUpn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationPropertiesInternal)Property).UserUpn = value ?? null; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader0) is string __headerRetryAfterHeader0 ? int.TryParse( __headerRetryAfterHeader0, out int __headerRetryAfterHeader0Value ) ? __headerRetryAfterHeader0Value : default(int?) : default(int?); + } + } + + /// Creates an new instance. + public OrganizationResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Organization Resource by Astronomer + public partial interface IOrganizationResource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? OfferDetailEndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning state of the resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserUpn { get; set; } + + } + /// Organization Resource by Astronomer + internal partial interface IOrganizationResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal + { + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Identity { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityPrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityTenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails MarketplaceOfferDetail { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + global::System.DateTime? OfferDetailEndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// Workspace Id in partner's system + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + + int? RetryAfter { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get; set; } + /// Email address of the user + string UserEmailAddress { get; set; } + /// First name of the user + string UserFirstName { get; set; } + /// Last name of the user + string UserLastName { get; set; } + /// User's phone number + string UserPhoneNumber { get; set; } + /// User's principal name + string UserUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.json.cs new file mode 100644 index 00000000000..15e02694143 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResource.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Organization Resource by Astronomer + public partial class OrganizationResource + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResource(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationProperties.FromJson(__jsonProperties) : _property;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4.FromJson(__jsonIdentity) : _identity;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs new file mode 100644 index 00000000000..7b136368a46 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The response of a OrganizationResource list operation. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceListResultTypeConverter))] + public partial class OrganizationResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResourceListResult(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.Astro.Models.IOrganizationResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResourceListResult(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.Astro.Models.IOrganizationResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResourceListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationResourceListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The response of a OrganizationResource list operation. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceListResultTypeConverter))] + public partial interface IOrganizationResourceListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs new file mode 100644 index 00000000000..b4d69bf3fdb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResourceListResult.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.cs new file mode 100644 index 00000000000..14b43aa8475 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The response of a OrganizationResource list operation. + public partial class OrganizationResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The OrganizationResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OrganizationResourceListResult() + { + + } + } + /// The response of a OrganizationResource list operation. + public partial interface IOrganizationResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The OrganizationResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The OrganizationResource items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a OrganizationResource list operation. + internal partial interface IOrganizationResourceListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The OrganizationResource items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs new file mode 100644 index 00000000000..d8920795861 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The response of a OrganizationResource list operation. + public partial class OrganizationResourceListResult + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationResourceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource) (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.PowerShell.cs new file mode 100644 index 00000000000..e30fba82842 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.PowerShell.cs @@ -0,0 +1,442 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The type used for update operations of the OrganizationResource. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceUpdateTypeConverter))] + public partial class OrganizationResourceUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResourceUpdate(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.Astro.Models.IOrganizationResourceUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResourceUpdate(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.Astro.Models.IOrganizationResourceUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResourceUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4TypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyProvisioningState, 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 OrganizationResourceUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4TypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal)this).SingleSignOnPropertyProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The type used for update operations of the OrganizationResource. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceUpdateTypeConverter))] + public partial interface IOrganizationResourceUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.TypeConverter.cs new file mode 100644 index 00000000000..88177931fae --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResourceUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResourceUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResourceUpdate.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.cs new file mode 100644 index 00000000000..bc4cfad3385 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.cs @@ -0,0 +1,611 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The type used for update operations of the OrganizationResource. + public partial class OrganizationResourceUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4()); set => this._identity = value; } + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId; } + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceSubscriptionStatus = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).PrincipalId = value; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4Internal)Identity).TenantId = value; } + + /// Internal Acessors for Marketplace + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.Marketplace { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).Marketplace; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).Marketplace = value; } + + /// Internal Acessors for MarketplaceOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.MarketplaceOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceOfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).MarketplaceOfferDetail = value; } + + /// Internal Acessors for OfferDetailEndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailEndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailEndDate = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.PartnerOrganizationProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationProperty = value; } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceUpdateProperties()); set { {_property = value;} } } + + /// Internal Acessors for SingleSignOnPropertyProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyProvisioningState = value; } + + /// Internal Acessors for User + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateInternal.User { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).User; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).User = value; } + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailEndDate; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailOfferId = value ?? null; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPlanId = value ?? null; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailPublisherId = value ?? null; } + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailRenewalMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailRenewalMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailRenewalMode = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailTermId = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).OfferDetailTermUnit = value ?? null; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName = value ?? null; } + + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceId = value ?? null; } + + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).PartnerOrganizationPropertyWorkspaceName = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceUpdateProperties()); set => this._property = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertyProvisioningState; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Tags()); set => this._tag = value; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserEmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserEmailAddress = value ?? null; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserFirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserFirstName = value ?? null; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserLastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserLastName = value ?? null; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserPhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserPhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserUpn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)Property).UserUpn = value ?? null; } + + /// Creates an new instance. + public OrganizationResourceUpdate() + { + + } + } + /// The type used for update operations of the OrganizationResource. + public partial interface IOrganizationResourceUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? OfferDetailEndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserUpn { get; set; } + + } + /// The type used for update operations of the OrganizationResource. + internal partial interface IOrganizationResourceUpdateInternal + + { + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IManagedServiceIdentityV4 Identity { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityPrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityTenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned, UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails MarketplaceOfferDetail { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + global::System.DateTime? OfferDetailEndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// Workspace Id in partner's system + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties Property { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get; set; } + /// Email address of the user + string UserEmailAddress { get; set; } + /// First name of the user + string UserFirstName { get; set; } + /// Last name of the user + string UserLastName { get; set; } + /// User's phone number + string UserPhoneNumber { get; set; } + /// User's principal name + string UserUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.json.cs new file mode 100644 index 00000000000..4232955ee87 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdate.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The type used for update operations of the OrganizationResource. + public partial class OrganizationResourceUpdate + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationResourceUpdate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResourceUpdate(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ManagedServiceIdentityV4.FromJson(__jsonIdentity) : _identity;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResourceUpdateProperties.FromJson(__jsonProperties) : _property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Tags.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.PowerShell.cs new file mode 100644 index 00000000000..914d2a6f9e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.PowerShell.cs @@ -0,0 +1,388 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The updatable properties of the OrganizationResource. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceUpdatePropertiesTypeConverter))] + public partial class OrganizationResourceUpdateProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResourceUpdateProperties(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.Astro.Models.IOrganizationResourceUpdateProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResourceUpdateProperties(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.Astro.Models.IOrganizationResourceUpdateProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResourceUpdateProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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 OrganizationResourceUpdateProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Marketplace")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).Marketplace = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails) content.GetValueForProperty("Marketplace",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).Marketplace, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("User")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).User = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails) content.GetValueForProperty("User",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).User, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails) content.GetValueForProperty("MarketplaceOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserEmailAddress = (string) content.GetValueForProperty("UserEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailRenewalMode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailRenewalMode = (string) content.GetValueForProperty("OfferDetailRenewalMode",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailRenewalMode, global::System.Convert.ToString); + } + if (content.Contains("UserFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserFirstName = (string) content.GetValueForProperty("UserFirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserLastName = (string) content.GetValueForProperty("UserLastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserLastName, global::System.Convert.ToString); + } + if (content.Contains("UserUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserUpn = (string) content.GetValueForProperty("UserUpn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserUpn, global::System.Convert.ToString); + } + if (content.Contains("UserPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserPhoneNumber = (string) content.GetValueForProperty("UserPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).UserPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyWorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName = (string) content.GetValueForProperty("PartnerOrganizationPropertyWorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).PartnerOrganizationPropertyWorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailEndDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailEndDate = (global::System.DateTime?) content.GetValueForProperty("OfferDetailEndDate",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).OfferDetailEndDate, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The updatable properties of the OrganizationResource. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceUpdatePropertiesTypeConverter))] + public partial interface IOrganizationResourceUpdateProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.TypeConverter.cs new file mode 100644 index 00000000000..aebf21d70ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceUpdatePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResourceUpdateProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResourceUpdateProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResourceUpdateProperties.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.cs new file mode 100644 index 00000000000..afd7ec0de21 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.cs @@ -0,0 +1,500 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The updatable properties of the OrganizationResource. + public partial class OrganizationResourceUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails _marketplace; + + /// Marketplace details of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get => (this._marketplace = this._marketplace ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails()); set => this._marketplace = value; } + + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string MarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).SubscriptionStatus = value ?? null; } + + /// Internal Acessors for Marketplace + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.Marketplace { get => (this._marketplace = this._marketplace ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails()); set { {_marketplace = value;} } } + + /// Internal Acessors for MarketplaceOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.MarketplaceOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetail = value; } + + /// Internal Acessors for OfferDetailEndDate + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties()); set { {_partnerOrganizationProperty = value;} } } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty = value; } + + /// Internal Acessors for SingleSignOnPropertyProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState = value; } + + /// Internal Acessors for User + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdatePropertiesInternal.User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails()); set { {_user = value;} } } + + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? OfferDetailEndDate { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailEndDate; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailOfferId = value ?? null; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanId = value ?? null; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailPublisherId = value ?? null; } + + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailRenewalMode { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailRenewalMode; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailRenewalMode = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermId = value ?? null; } + + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetailsInternal)Marketplace).OfferDetailTermUnit = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties _partnerOrganizationProperty; + + /// Organization properties + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties()); set => this._partnerOrganizationProperty = value; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName = value ?? null; } + + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceId = value ?? null; } + + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyWorkspaceName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).WorkspaceName = value ?? null; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyProvisioningState; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails _user; + + /// Details of the user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get => (this._user = this._user ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails()); set => this._user = value; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).EmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).EmailAddress = value ?? null; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).FirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).FirstName = value ?? null; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).LastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).LastName = value ?? null; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).PhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).PhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string UserUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).Upn; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)User).Upn = value ?? null; } + + /// Creates an new instance. + public OrganizationResourceUpdateProperties() + { + + } + } + /// The updatable properties of the OrganizationResource. + public partial interface IOrganizationResourceUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Azure subscription id for the the marketplace offer is purchased from + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Current subscription end date and time", + SerializedName = @"endDate", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? OfferDetailEndDate { get; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserUpn { get; set; } + + } + /// The updatable properties of the OrganizationResource. + internal partial interface IOrganizationResourceUpdatePropertiesInternal + + { + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IMarketplaceDetails Marketplace { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOfferDetails MarketplaceOfferDetail { get; set; } + /// Azure subscription id for the the marketplace offer is purchased from + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Current subscription end date and time + global::System.DateTime? OfferDetailEndDate { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Subscription renewal mode + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + string OfferDetailRenewalMode { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermId { get; set; } + /// Plan Display Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// Workspace Id in partner's system + string PartnerOrganizationPropertyWorkspaceId { get; set; } + /// Workspace name in partner's system + string PartnerOrganizationPropertyWorkspaceName { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails User { get; set; } + /// Email address of the user + string UserEmailAddress { get; set; } + /// First name of the user + string UserFirstName { get; set; } + /// Last name of the user + string UserLastName { get; set; } + /// User's phone number + string UserPhoneNumber { get; set; } + /// User's principal name + string UserUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.json.cs new file mode 100644 index 00000000000..c1a13b6c209 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationResourceUpdateProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The updatable properties of the OrganizationResource. + public partial class OrganizationResourceUpdateProperties + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceUpdateProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationResourceUpdateProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResourceUpdateProperties(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplace = If( json?.PropertyT("marketplace"), out var __jsonMarketplace) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.MarketplaceDetails.FromJson(__jsonMarketplace) : _marketplace;} + {_user = If( json?.PropertyT("user"), out var __jsonUser) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserDetails.FromJson(__jsonUser) : _user;} + {_partnerOrganizationProperty = If( json?.PropertyT("partnerOrganizationProperties"), out var __jsonPartnerOrganizationProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.PartnerOrganizationProperties.FromJson(__jsonPartnerOrganizationProperties) : _partnerOrganizationProperty;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._marketplace ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._marketplace.ToJson(null,serializationMode) : null, "marketplace" ,container.Add ); + AddIf( null != this._user ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._user.ToJson(null,serializationMode) : null, "user" ,container.Add ); + AddIf( null != this._partnerOrganizationProperty ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._partnerOrganizationProperty.ToJson(null,serializationMode) : null, "partnerOrganizationProperties" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..f7fd33bf5e1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(OrganizationsDeleteAcceptedResponseHeadersTypeConverter))] + public partial class OrganizationsDeleteAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationsDeleteAcceptedResponseHeaders(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.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationsDeleteAcceptedResponseHeaders(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.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationsDeleteAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationsDeleteAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(OrganizationsDeleteAcceptedResponseHeadersTypeConverter))] + public partial interface IOrganizationsDeleteAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..5bc362d4082 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationsDeleteAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationsDeleteAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationsDeleteAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationsDeleteAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..0284dd0291e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class OrganizationsDeleteAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// + /// Creates an new instance. + /// + public OrganizationsDeleteAcceptedResponseHeaders() + { + + } + } + public partial interface IOrganizationsDeleteAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface IOrganizationsDeleteAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..748015ad3c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class OrganizationsDeleteAcceptedResponseHeaders + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsDeleteAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationsDeleteAcceptedResponseHeaders(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationsDeleteAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..1ad8f017e38 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(OrganizationsUpdateAcceptedResponseHeadersTypeConverter))] + public partial class OrganizationsUpdateAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationsUpdateAcceptedResponseHeaders(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.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationsUpdateAcceptedResponseHeaders(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.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationsUpdateAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationsUpdateAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(OrganizationsUpdateAcceptedResponseHeadersTypeConverter))] + public partial interface IOrganizationsUpdateAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..50e010d46c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationsUpdateAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationsUpdateAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationsUpdateAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationsUpdateAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..21940fac2b4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class OrganizationsUpdateAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// + /// Creates an new instance. + /// + public OrganizationsUpdateAcceptedResponseHeaders() + { + + } + } + public partial interface IOrganizationsUpdateAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface IOrganizationsUpdateAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..5900c809a34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class OrganizationsUpdateAcceptedResponseHeaders + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationsUpdateAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new OrganizationsUpdateAcceptedResponseHeaders(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationsUpdateAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs new file mode 100644 index 00000000000..1681babd1df --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs @@ -0,0 +1,234 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Properties specific to Partner's organization + [System.ComponentModel.TypeConverter(typeof(PartnerOrganizationPropertiesTypeConverter))] + public partial class PartnerOrganizationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PartnerOrganizationProperties(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.Astro.Models.IPartnerOrganizationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PartnerOrganizationProperties(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.Astro.Models.IPartnerOrganizationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PartnerOrganizationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("SingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("OrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId = (string) content.GetValueForProperty("OrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceId = (string) content.GetValueForProperty("WorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceName = (string) content.GetValueForProperty("WorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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 PartnerOrganizationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties) content.GetValueForProperty("SingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("OrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId = (string) content.GetValueForProperty("OrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceId = (string) content.GetValueForProperty("WorkspaceId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceId, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("WorkspaceName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceName = (string) content.GetValueForProperty("WorkspaceName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).WorkspaceName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState = (string) content.GetValueForProperty("SingleSignOnPropertyProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Partner's organization + [System.ComponentModel.TypeConverter(typeof(PartnerOrganizationPropertiesTypeConverter))] + public partial interface IPartnerOrganizationProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs new file mode 100644 index 00000000000..7fe61648298 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PartnerOrganizationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PartnerOrganizationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PartnerOrganizationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PartnerOrganizationProperties.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.cs new file mode 100644 index 00000000000..041ccbb5ab1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Partner's organization + public partial class PartnerOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal + { + + /// Internal Acessors for SingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal.SingleSignOnProperty { get => (this._singleSignOnProperty = this._singleSignOnProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnProperties()); set { {_singleSignOnProperty = value;} } } + + /// Internal Acessors for SingleSignOnPropertyProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationPropertiesInternal.SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).ProvisioningState = value; } + + /// Backing field for property. + private string _organizationId; + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string OrganizationId { get => this._organizationId; set => this._organizationId = value; } + + /// Backing field for property. + private string _organizationName; + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string OrganizationName { get => this._organizationName; set => this._organizationName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties _singleSignOnProperty; + + /// Single Sign On properties for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties SingleSignOnProperty { get => (this._singleSignOnProperty = this._singleSignOnProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnProperties()); set => this._singleSignOnProperty = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).AadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).AadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).EnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).EnterpriseAppId = value ?? null; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).ProvisioningState; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnUrl = value ?? null; } + + /// Backing field for property. + private string _workspaceId; + + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string WorkspaceId { get => this._workspaceId; set => this._workspaceId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// Creates an new instance. + public PartnerOrganizationProperties() + { + + } + } + /// Properties specific to Partner's organization + public partial interface IPartnerOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string OrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string OrganizationName { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Workspace Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + string WorkspaceId { get; set; } + /// Workspace name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + string WorkspaceName { get; set; } + + } + /// Properties specific to Partner's organization + internal partial interface IPartnerOrganizationPropertiesInternal + + { + /// Organization Id in partner's system + string OrganizationId { get; set; } + /// Organization name in partner's system + string OrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties SingleSignOnProperty { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string SingleSignOnPropertyProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Workspace Id in partner's system + string WorkspaceId { get; set; } + /// Workspace name in partner's system + string WorkspaceName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.json.cs new file mode 100644 index 00000000000..6248754f916 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/PartnerOrganizationProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Partner's organization + public partial class PartnerOrganizationProperties + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IPartnerOrganizationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new PartnerOrganizationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal PartnerOrganizationProperties(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_singleSignOnProperty = If( json?.PropertyT("singleSignOnProperties"), out var __jsonSingleSignOnProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SingleSignOnProperties.FromJson(__jsonSingleSignOnProperties) : _singleSignOnProperty;} + {_organizationId = If( json?.PropertyT("organizationId"), out var __jsonOrganizationId) ? (string)__jsonOrganizationId : (string)_organizationId;} + {_workspaceId = If( json?.PropertyT("workspaceId"), out var __jsonWorkspaceId) ? (string)__jsonWorkspaceId : (string)_workspaceId;} + {_organizationName = If( json?.PropertyT("organizationName"), out var __jsonOrganizationName) ? (string)__jsonOrganizationName : (string)_organizationName;} + {_workspaceName = If( json?.PropertyT("workspaceName"), out var __jsonWorkspaceName) ? (string)__jsonWorkspaceName : (string)_workspaceName;} + 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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._singleSignOnProperty ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._singleSignOnProperty.ToJson(null,serializationMode) : null, "singleSignOnProperties" ,container.Add ); + AddIf( null != (((object)this._organizationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._organizationId.ToString()) : null, "organizationId" ,container.Add ); + AddIf( null != (((object)this._workspaceId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._workspaceId.ToString()) : null, "workspaceId" ,container.Add ); + AddIf( null != (((object)this._organizationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._organizationName.ToString()) : null, "organizationName" ,container.Add ); + AddIf( null != (((object)this._workspaceName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._workspaceName.ToString()) : null, "workspaceName" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..3f472765a14 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Resource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Resource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..8279c6bfd06 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Resource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Resource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Resource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..f70bfead022 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.cs @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataLastModifiedBy { get; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of the resource. E.g. ""Microsoft.Compute/virtualMachines"" or ""Microsoft.Storage/storageAccounts""", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData SystemData { get; set; } + /// The timestamp of resource creation (UTC). + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// The identity that last modified the resource. + string SystemDataLastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..42999e1fbb2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Resource.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs new file mode 100644 index 00000000000..4ba8ee83a84 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Properties specific to Single Sign On Resource + [System.ComponentModel.TypeConverter(typeof(SingleSignOnPropertiesTypeConverter))] + public partial class SingleSignOnProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SingleSignOnProperties(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.Astro.Models.ISingleSignOnProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SingleSignOnProperties(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.Astro.Models.ISingleSignOnProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SingleSignOnProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState = (string) content.GetValueForProperty("SingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId = (string) content.GetValueForProperty("EnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("AadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).AadDomain = (System.Collections.Generic.List) content.GetValueForProperty("AadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).AadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SingleSignOnProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState = (string) content.GetValueForProperty("SingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId = (string) content.GetValueForProperty("EnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("AadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).AadDomain = (System.Collections.Generic.List) content.GetValueForProperty("AadDomain",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).AadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal)this).ProvisioningState, 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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Single Sign On Resource + [System.ComponentModel.TypeConverter(typeof(SingleSignOnPropertiesTypeConverter))] + public partial interface ISingleSignOnProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs new file mode 100644 index 00000000000..5f1ac7be2eb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SingleSignOnPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SingleSignOnProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SingleSignOnProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SingleSignOnProperties.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.cs new file mode 100644 index 00000000000..275d705a8bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Single Sign On Resource + public partial class SingleSignOnProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _aadDomain; + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public System.Collections.Generic.List AadDomain { get => this._aadDomain; set => this._aadDomain = value; } + + /// Backing field for property. + private string _enterpriseAppId; + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string EnterpriseAppId { get => this._enterpriseAppId; set => this._enterpriseAppId = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _singleSignOnState; + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string SingleSignOnState { get => this._singleSignOnState; set => this._singleSignOnState = value; } + + /// Backing field for property. + private string _singleSignOnUrl; + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string SingleSignOnUrl { get => this._singleSignOnUrl; set => this._singleSignOnUrl = value; } + + /// Creates an new instance. + public SingleSignOnProperties() + { + + } + } + /// Properties specific to Single Sign On Resource + public partial interface ISingleSignOnProperties : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseAppId { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnUrl { get; set; } + + } + /// Properties specific to Single Sign On Resource + internal partial interface ISingleSignOnPropertiesInternal + + { + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List AadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string EnterpriseAppId { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnUrl { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.json.cs new file mode 100644 index 00000000000..9c9c0dd7c77 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SingleSignOnProperties.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Properties specific to Single Sign On Resource + public partial class SingleSignOnProperties + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISingleSignOnProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new SingleSignOnProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal SingleSignOnProperties(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_singleSignOnState = If( json?.PropertyT("singleSignOnState"), out var __jsonSingleSignOnState) ? (string)__jsonSingleSignOnState : (string)_singleSignOnState;} + {_enterpriseAppId = If( json?.PropertyT("enterpriseAppId"), out var __jsonEnterpriseAppId) ? (string)__jsonEnterpriseAppId : (string)_enterpriseAppId;} + {_singleSignOnUrl = If( json?.PropertyT("singleSignOnUrl"), out var __jsonSingleSignOnUrl) ? (string)__jsonSingleSignOnUrl : (string)_singleSignOnUrl;} + {_aadDomain = If( json?.PropertyT("aadDomains"), out var __jsonAadDomains) ? If( __jsonAadDomains as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(string) (__u is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _aadDomain;} + {_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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._singleSignOnState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._singleSignOnState.ToString()) : null, "singleSignOnState" ,container.Add ); + AddIf( null != (((object)this._enterpriseAppId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._enterpriseAppId.ToString()) : null, "enterpriseAppId" ,container.Add ); + AddIf( null != (((object)this._singleSignOnUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._singleSignOnUrl.ToString()) : null, "singleSignOnUrl" ,container.Add ); + if (null != this._aadDomain) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.XNodeArray(); + foreach( var __x in this._aadDomain ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("aadDomains",__w); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..bf29592bd48 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..6ac6939a020 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..21b9b18aa73 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; set => this._createdAt = value; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; set => this._createdBy = value; } + + /// Backing field for property. + private string _createdByType; + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; set => this._createdByType = value; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; set => this._lastModifiedAt = value; } + + /// Backing field for property. + private string _lastModifiedBy; + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string LastModifiedBy { get => this._lastModifiedBy; set => this._lastModifiedBy = value; } + + /// Backing field for property. + private string _lastModifiedByType; + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string LastModifiedByType { get => this._lastModifiedByType; set => this._lastModifiedByType = value; } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp of resource creation (UTC). + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..e5b34154826 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/SystemData.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_lastModifiedBy = If( json?.PropertyT("lastModifiedBy"), out var __jsonLastModifiedBy) ? (string)__jsonLastModifiedBy : (string)_lastModifiedBy;} + {_lastModifiedByType = If( json?.PropertyT("lastModifiedByType"), out var __jsonLastModifiedByType) ? (string)__jsonLastModifiedByType : (string)_lastModifiedByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + AddIf( null != (((object)this._lastModifiedBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.PowerShell.cs new file mode 100644 index 00000000000..b7a5d554b78 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// Resource tags. + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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.Astro.Models.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.Astro.Models.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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 + // 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 Tags(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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.TypeConverter.cs new file mode 100644 index 00000000000..32f95564899 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.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 type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.cs new file mode 100644 index 00000000000..60e0d163245 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Resource tags. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITagsInternal + { + + /// Creates an new instance. + public Tags() + { + + } + } + /// Resource tags. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.dictionary.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.dictionary.cs new file mode 100644 index 00000000000..7e9a9cf4614 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.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.Astro.Models.Tags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.json.cs new file mode 100644 index 00000000000..2fd365ef15c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/Tags.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// Resource tags. + 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..03bd31e2141 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.PowerShell.cs @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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.Astro.Models.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.Astro.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// 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 + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..4c8739e3951 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.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 + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..84820be102e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Tags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.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 that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = 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.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get; set; } + + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..27890335856 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/TrackedResource.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.Tags.FromJson(__jsonTags) : _tag;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..a09bd087dd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesTypeConverter))] + public partial class UserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentities(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.Astro.Models.IUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentities(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.Astro.Models.IUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentities(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 UserAssignedIdentities(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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesTypeConverter))] + public partial interface IUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..16b1c5cea0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentities.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.cs new file mode 100644 index 00000000000..66c5ca73aab --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class UserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentitiesInternal + { + + /// Creates an new instance. + public UserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..b98ff9d7075 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + public partial class UserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity 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.Astro.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.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.json.cs new file mode 100644 index 00000000000..ec85f7322b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentities.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class UserAssignedIdentities + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new UserAssignedIdentities(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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + /// + internal UserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity.FromJson(j) ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..6feeba084c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// User assigned identity properties + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityTypeConverter))] + public partial class UserAssignedIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentity(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.Astro.Models.IUserAssignedIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentity(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.Astro.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).ClientId, 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 UserAssignedIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal)this).ClientId, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// User assigned identity properties + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityTypeConverter))] + public partial interface IUserAssignedIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..8f1285342aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentity.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..fe8da0a9995 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// The principal ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Creates an new instance. + public UserAssignedIdentity() + { + + } + } + /// User assigned identity properties + public partial interface IUserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The client ID of the assigned identity.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// The principal ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The principal ID of the assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + + } + /// User assigned identity properties + internal partial interface IUserAssignedIdentityInternal + + { + /// The client ID of the assigned identity. + string ClientId { get; set; } + /// The principal ID of the assigned identity. + string PrincipalId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..bdba9b2bd39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserAssignedIdentity.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new UserAssignedIdentity(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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)_principalId;} + {_clientId = If( json?.PropertyT("clientId"), out var __jsonClientId) ? (string)__jsonClientId : (string)_clientId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.PowerShell.cs new file mode 100644 index 00000000000..975668aff19 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// User details for an organization + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial class UserDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserDetails(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.Astro.Models.IUserDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserDetails(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.Astro.Models.IUserDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("FirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).FirstName = (string) content.GetValueForProperty("FirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).FirstName, global::System.Convert.ToString); + } + if (content.Contains("LastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).LastName = (string) content.GetValueForProperty("LastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).LastName, global::System.Convert.ToString); + } + if (content.Contains("EmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).EmailAddress = (string) content.GetValueForProperty("EmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).EmailAddress, global::System.Convert.ToString); + } + if (content.Contains("Upn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).Upn = (string) content.GetValueForProperty("Upn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).Upn, global::System.Convert.ToString); + } + if (content.Contains("PhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).PhoneNumber = (string) content.GetValueForProperty("PhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).PhoneNumber, 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 UserDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("FirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).FirstName = (string) content.GetValueForProperty("FirstName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).FirstName, global::System.Convert.ToString); + } + if (content.Contains("LastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).LastName = (string) content.GetValueForProperty("LastName",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).LastName, global::System.Convert.ToString); + } + if (content.Contains("EmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).EmailAddress = (string) content.GetValueForProperty("EmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).EmailAddress, global::System.Convert.ToString); + } + if (content.Contains("Upn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).Upn = (string) content.GetValueForProperty("Upn",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).Upn, global::System.Convert.ToString); + } + if (content.Contains("PhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).PhoneNumber = (string) content.GetValueForProperty("PhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal)this).PhoneNumber, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// User details for an organization + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial interface IUserDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.TypeConverter.cs new file mode 100644 index 00000000000..1188fdc760d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserDetails.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.cs new file mode 100644 index 00000000000..0b50a8e6875 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// User details for an organization + public partial class UserDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetailsInternal + { + + /// Backing field for property. + private string _emailAddress; + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string EmailAddress { get => this._emailAddress; set => this._emailAddress = value; } + + /// Backing field for property. + private string _firstName; + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string FirstName { get => this._firstName; set => this._firstName = value; } + + /// Backing field for property. + private string _lastName; + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string LastName { get => this._lastName; set => this._lastName = value; } + + /// Backing field for property. + private string _phoneNumber; + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string PhoneNumber { get => this._phoneNumber; set => this._phoneNumber = value; } + + /// Backing field for property. + private string _upn; + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Origin(Microsoft.Azure.PowerShell.Cmdlets.Astro.PropertyOrigin.Owned)] + public string Upn { get => this._upn; set => this._upn = value; } + + /// Creates an new instance. + public UserDetails() + { + + } + } + /// User details for an organization + public partial interface IUserDetails : + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IJsonSerializable + { + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string EmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string FirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string LastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string PhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string Upn { get; set; } + + } + /// User details for an organization + internal partial interface IUserDetailsInternal + + { + /// Email address of the user + string EmailAddress { get; set; } + /// First name of the user + string FirstName { get; set; } + /// Last name of the user + string LastName { get; set; } + /// User's phone number + string PhoneNumber { get; set; } + /// User's principal name + string Upn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.json.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.json.cs new file mode 100644 index 00000000000..53d98d431cb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/api/Models/UserDetails.json.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + + /// User details for an organization + public partial class UserDetails + { + + /// + /// 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.Astro.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails. + public static Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IUserDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json ? new UserDetails(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.Astro.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._firstName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._firstName.ToString()) : null, "firstName" ,container.Add ); + AddIf( null != (((object)this._lastName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._lastName.ToString()) : null, "lastName" ,container.Add ); + AddIf( null != (((object)this._emailAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._emailAddress.ToString()) : null, "emailAddress" ,container.Add ); + AddIf( null != (((object)this._upn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._upn.ToString()) : null, "upn" ,container.Add ); + AddIf( null != (((object)this._phoneNumber)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonString(this._phoneNumber.ToString()) : null, "phoneNumber" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject instance to deserialize from. + internal UserDetails(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_firstName = If( json?.PropertyT("firstName"), out var __jsonFirstName) ? (string)__jsonFirstName : (string)_firstName;} + {_lastName = If( json?.PropertyT("lastName"), out var __jsonLastName) ? (string)__jsonLastName : (string)_lastName;} + {_emailAddress = If( json?.PropertyT("emailAddress"), out var __jsonEmailAddress) ? (string)__jsonEmailAddress : (string)_emailAddress;} + {_upn = If( json?.PropertyT("upn"), out var __jsonUpn) ? (string)__jsonUpn : (string)_upn;} + {_phoneNumber = If( json?.PropertyT("phoneNumber"), out var __jsonPhoneNumber) ? (string)__jsonPhoneNumber : (string)_phoneNumber;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOperation_List.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOperation_List.cs new file mode 100644 index 00000000000..66df4cae068 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOperation_List.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Astronomer.Astro/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAstroOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/providers/Astronomer.Astro/operations", ApiVersion = "2024-08-27")] + public partial class GetAzAstroOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzAstroOperation_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.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOperationListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_Get.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_Get.cs new file mode 100644 index 00000000000..b40a507c8ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_Get.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// Get a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAstroOrganization_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"Get a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class GetAzAstroOrganization_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzAstroOrganization_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.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_GetViaIdentity.cs new file mode 100644 index 00000000000..9298c6eb231 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_GetViaIdentity.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// Get a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAstroOrganization_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"Get a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class GetAzAstroOrganization_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity 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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzAstroOrganization_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.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsGetViaIdentity(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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List.cs new file mode 100644 index 00000000000..412c72e54d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List.cs @@ -0,0 +1,518 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// List OrganizationResource resources by resource group + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAstroOrganization_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"List OrganizationResource resources by resource group")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations", ApiVersion = "2024-08-27")] + public partial class GetAzAstroOrganization_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzAstroOrganization_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.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult + /// 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.Astro.Models.IOrganizationResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List1.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List1.cs new file mode 100644 index 00000000000..3da18c184c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/GetAzAstroOrganization_List1.cs @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// List OrganizationResource resources by subscription ID + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Astronomer.Astro/organizations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzAstroOrganization_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"List OrganizationResource resources by subscription ID")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Astronomer.Astro/organizations", ApiVersion = "2024-08-27")] + public partial class GetAzAstroOrganization_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzAstroOrganization_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.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResourceListResult + /// 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.Astro.Models.IOrganizationResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateExpanded.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateExpanded.cs new file mode 100644 index 00000000000..d98174070ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateExpanded.cs @@ -0,0 +1,899 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAstroOrganization_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class NewAzAstroOrganization_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Astronomer + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public global::System.Management.Automation.SwitchParameter EnableSystemAssignedIdentity { set => _resourceBody.IdentityType = value.IsPresent ? "SystemAssigned": null ; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Azure subscription id for the the marketplace offer is purchased from + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure subscription id for the the marketplace offer is purchased from")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceSubscriptionId { get => _resourceBody.MarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceSubscriptionStatus { get => _resourceBody.MarketplaceSubscriptionStatus ?? null; set => _resourceBody.MarketplaceSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Subscription renewal mode + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Subscription renewal mode")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + public string OfferDetailRenewalMode { get => _resourceBody.OfferDetailRenewalMode ?? null; set => _resourceBody.OfferDetailRenewalMode = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// Workspace Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceId { get => _resourceBody.PartnerOrganizationPropertyWorkspaceId ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceId = value; } + + /// Workspace name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceName { get => _resourceBody.PartnerOrganizationPropertyWorkspaceName ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserEmailAddress { get => _resourceBody.UserEmailAddress ?? null; set => _resourceBody.UserEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserFirstName { get => _resourceBody.UserFirstName ?? null; set => _resourceBody.UserFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserLastName { get => _resourceBody.UserLastName ?? null; set => _resourceBody.UserLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserPhoneNumber { get => _resourceBody.UserPhoneNumber ?? null; set => _resourceBody.UserPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserUpn { get => _resourceBody.UserUpn ?? null; set => _resourceBody.UserUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAstroOrganization_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.NewAzAstroOrganization_CreateExpanded Clone() + { + var clone = new NewAzAstroOrganization_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._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzAstroOrganization_CreateExpanded() + { + + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.OrganizationsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..d32430dcd88 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaIdentityExpanded.cs @@ -0,0 +1,877 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAstroOrganization_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class NewAzAstroOrganization_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Astronomer + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public global::System.Management.Automation.SwitchParameter EnableSystemAssignedIdentity { set => _resourceBody.IdentityType = value.IsPresent ? "SystemAssigned": null ; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity 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 = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Azure subscription id for the the marketplace offer is purchased from + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure subscription id for the the marketplace offer is purchased from")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceSubscriptionId { get => _resourceBody.MarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceSubscriptionStatus { get => _resourceBody.MarketplaceSubscriptionStatus ?? null; set => _resourceBody.MarketplaceSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Subscription renewal mode + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Subscription renewal mode")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + public string OfferDetailRenewalMode { get => _resourceBody.OfferDetailRenewalMode ?? null; set => _resourceBody.OfferDetailRenewalMode = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// Workspace Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceId { get => _resourceBody.PartnerOrganizationPropertyWorkspaceId ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceId = value; } + + /// Workspace name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceName { get => _resourceBody.PartnerOrganizationPropertyWorkspaceName ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserEmailAddress { get => _resourceBody.UserEmailAddress ?? null; set => _resourceBody.UserEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserFirstName { get => _resourceBody.UserFirstName ?? null; set => _resourceBody.UserFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserLastName { get => _resourceBody.UserLastName ?? null; set => _resourceBody.UserLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserPhoneNumber { get => _resourceBody.UserPhoneNumber ?? null; set => _resourceBody.UserPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserUpn { get => _resourceBody.UserUpn ?? null; set => _resourceBody.UserUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAstroOrganization_CreateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.NewAzAstroOrganization_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzAstroOrganization_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzAstroOrganization_CreateViaIdentityExpanded() + { + + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + this.PreProcessManagedIdentityParameters(); + await this.Client.OrganizationsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate); + } + 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + this.PreProcessManagedIdentityParameters(); + await this.Client.OrganizationsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..658f4ab86d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonFilePath.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAstroOrganization_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.NotSuggestDefaultParameterSet] + public partial class NewAzAstroOrganization_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAstroOrganization_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.NewAzAstroOrganization_CreateViaJsonFilePath Clone() + { + var clone = new NewAzAstroOrganization_CreateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzAstroOrganization_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonString.cs new file mode 100644 index 00000000000..43b4f87a825 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/NewAzAstroOrganization_CreateViaJsonString.cs @@ -0,0 +1,603 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzAstroOrganization_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.NotSuggestDefaultParameterSet] + public partial class NewAzAstroOrganization_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzAstroOrganization_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.NewAzAstroOrganization_CreateViaJsonString Clone() + { + var clone = new NewAzAstroOrganization_CreateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzAstroOrganization_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_Delete.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_Delete.cs new file mode 100644 index 00000000000..43066ae7249 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_Delete.cs @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// Delete a OrganizationResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzAstroOrganization_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"Delete a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class RemoveAzAstroOrganization_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzAstroOrganization_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.RemoveAzAstroOrganization_Delete Clone() + { + var clone = new RemoveAzAstroOrganization_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzAstroOrganization_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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 / application/json + 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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_DeleteViaIdentity.cs new file mode 100644 index 00000000000..94d6cef518c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/RemoveAzAstroOrganization_DeleteViaIdentity.cs @@ -0,0 +1,586 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// Delete a OrganizationResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzAstroOrganization_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"Delete a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class RemoveAzAstroOrganization_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity 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.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzAstroOrganization_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.RemoveAzAstroOrganization_DeleteViaIdentity Clone() + { + var clone = new RemoveAzAstroOrganization_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsDeleteViaIdentity(InputObject.Id, onNoContent, 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzAstroOrganization_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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 / application/json + 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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateExpanded.cs new file mode 100644 index 00000000000..94d6b99bdbe --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateExpanded.cs @@ -0,0 +1,900 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzAstroOrganization_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + public partial class SetAzAstroOrganization_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Astronomer + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Azure subscription id for the the marketplace offer is purchased from + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure subscription id for the the marketplace offer is purchased from")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceSubscriptionId { get => _resourceBody.MarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceSubscriptionStatus { get => _resourceBody.MarketplaceSubscriptionStatus ?? null; set => _resourceBody.MarketplaceSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Subscription renewal mode + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Subscription renewal mode")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + public string OfferDetailRenewalMode { get => _resourceBody.OfferDetailRenewalMode ?? null; set => _resourceBody.OfferDetailRenewalMode = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// Workspace Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceId { get => _resourceBody.PartnerOrganizationPropertyWorkspaceId ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceId = value; } + + /// Workspace name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceName { get => _resourceBody.PartnerOrganizationPropertyWorkspaceName ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserEmailAddress { get => _resourceBody.UserEmailAddress ?? null; set => _resourceBody.UserEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserFirstName { get => _resourceBody.UserFirstName ?? null; set => _resourceBody.UserFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserLastName { get => _resourceBody.UserLastName ?? null; set => _resourceBody.UserLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserPhoneNumber { get => _resourceBody.UserPhoneNumber ?? null; set => _resourceBody.UserPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserUpn { get => _resourceBody.UserUpn ?? null; set => _resourceBody.UserUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzAstroOrganization_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.SetAzAstroOrganization_UpdateExpanded Clone() + { + var clone = new SetAzAstroOrganization_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.OrganizationsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzAstroOrganization_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..2604258ab52 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonFilePath.cs @@ -0,0 +1,606 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzAstroOrganization_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.NotSuggestDefaultParameterSet] + public partial class SetAzAstroOrganization_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzAstroOrganization_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.SetAzAstroOrganization_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzAstroOrganization_UpdateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzAstroOrganization_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonString.cs new file mode 100644 index 00000000000..696af615167 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/SetAzAstroOrganization_UpdateViaJsonString.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzAstroOrganization_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}", ApiVersion = "2024-08-27")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.NotSuggestDefaultParameterSet] + public partial class SetAzAstroOrganization_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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 Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzAstroOrganization_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.SetAzAstroOrganization_UpdateViaJsonString Clone() + { + var clone = new SetAzAstroOrganization_UpdateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzAstroOrganization_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateExpanded.cs new file mode 100644 index 00000000000..6f35a8e0298 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateExpanded.cs @@ -0,0 +1,999 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAstroOrganization_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + public partial class UpdateAzAstroOrganization_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Astronomer + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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; } } + + /// Azure subscription id for the the marketplace offer is purchased from + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure subscription id for the the marketplace offer is purchased from")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceSubscriptionId { get => _resourceBody.MarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceSubscriptionStatus { get => _resourceBody.MarketplaceSubscriptionStatus ?? null; set => _resourceBody.MarketplaceSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Subscription renewal mode + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Subscription renewal mode")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + public string OfferDetailRenewalMode { get => _resourceBody.OfferDetailRenewalMode ?? null; set => _resourceBody.OfferDetailRenewalMode = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// Workspace Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceId { get => _resourceBody.PartnerOrganizationPropertyWorkspaceId ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceId = value; } + + /// Workspace name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceName { get => _resourceBody.PartnerOrganizationPropertyWorkspaceName ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserEmailAddress { get => _resourceBody.UserEmailAddress ?? null; set => _resourceBody.UserEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserFirstName { get => _resourceBody.UserFirstName ?? null; set => _resourceBody.UserFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserLastName { get => _resourceBody.UserLastName ?? null; set => _resourceBody.UserLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserPhoneNumber { get => _resourceBody.UserPhoneNumber ?? null; set => _resourceBody.UserPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserUpn { get => _resourceBody.UserUpn ?? null; set => _resourceBody.UserUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAstroOrganization_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.UpdateAzAstroOrganization_UpdateExpanded Clone() + { + var clone = new UpdateAzAstroOrganization_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParametersWithGetResult() + { + bool supportsSystemAssignedIdentity = (true == this.EnableSystemAssignedIdentity || null == this.EnableSystemAssignedIdentity && true == _resourceBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _resourceBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _resourceBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned"; + } + else + { + _resourceBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.OrganizationsGetWithResult(SubscriptionId, ResourceGroupName, Name, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.OrganizationsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzAstroOrganization_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceSubscriptionStatus"))) + { + this.MarketplaceSubscriptionStatus = (string)(this.MyInvocation?.BoundParameters["MarketplaceSubscriptionStatus"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserEmailAddress"))) + { + this.UserEmailAddress = (string)(this.MyInvocation?.BoundParameters["UserEmailAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceSubscriptionId"))) + { + this.MarketplaceSubscriptionId = (string)(this.MyInvocation?.BoundParameters["MarketplaceSubscriptionId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailRenewalMode"))) + { + this.OfferDetailRenewalMode = (string)(this.MyInvocation?.BoundParameters["OfferDetailRenewalMode"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserFirstName"))) + { + this.UserFirstName = (string)(this.MyInvocation?.BoundParameters["UserFirstName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserLastName"))) + { + this.UserLastName = (string)(this.MyInvocation?.BoundParameters["UserLastName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserUpn"))) + { + this.UserUpn = (string)(this.MyInvocation?.BoundParameters["UserUpn"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserPhoneNumber"))) + { + this.UserPhoneNumber = (string)(this.MyInvocation?.BoundParameters["UserPhoneNumber"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyOrganizationId"))) + { + this.PartnerOrganizationPropertyOrganizationId = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyOrganizationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyWorkspaceId"))) + { + this.PartnerOrganizationPropertyWorkspaceId = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyWorkspaceId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyOrganizationName"))) + { + this.PartnerOrganizationPropertyOrganizationName = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyOrganizationName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyWorkspaceName"))) + { + this.PartnerOrganizationPropertyWorkspaceName = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyWorkspaceName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertyAadDomain"))) + { + this.SingleSignOnPropertyAadDomain = (string[])(this.MyInvocation?.BoundParameters["SingleSignOnPropertyAadDomain"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPublisherId"))) + { + this.OfferDetailPublisherId = (string)(this.MyInvocation?.BoundParameters["OfferDetailPublisherId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailOfferId"))) + { + this.OfferDetailOfferId = (string)(this.MyInvocation?.BoundParameters["OfferDetailOfferId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPlanId"))) + { + this.OfferDetailPlanId = (string)(this.MyInvocation?.BoundParameters["OfferDetailPlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPlanName"))) + { + this.OfferDetailPlanName = (string)(this.MyInvocation?.BoundParameters["OfferDetailPlanName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailTermUnit"))) + { + this.OfferDetailTermUnit = (string)(this.MyInvocation?.BoundParameters["OfferDetailTermUnit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailTermId"))) + { + this.OfferDetailTermId = (string)(this.MyInvocation?.BoundParameters["OfferDetailTermId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertySingleSignOnState"))) + { + this.SingleSignOnPropertySingleSignOnState = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertySingleSignOnState"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertyEnterpriseAppId"))) + { + this.SingleSignOnPropertyEnterpriseAppId = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertyEnterpriseAppId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertySingleSignOnUrl"))) + { + this.SingleSignOnPropertySingleSignOnUrl = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertySingleSignOnUrl"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..640ed50c044 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/cmdlets/UpdateAzAstroOrganization_UpdateViaIdentityExpanded.cs @@ -0,0 +1,979 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Astronomer.Astro/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzAstroOrganization_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Generated] + public partial class UpdateAzAstroOrganization_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Astronomer + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client => Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IAstroIdentity 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; } } + + /// Azure subscription id for the the marketplace offer is purchased from + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Azure subscription id for the the marketplace offer is purchased from")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Azure subscription id for the the marketplace offer is purchased from", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceSubscriptionId { get => _resourceBody.MarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceSubscriptionStatus { get => _resourceBody.MarketplaceSubscriptionStatus ?? null; set => _resourceBody.MarketplaceSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Subscription renewal mode + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Subscription renewal mode")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Subscription renewal mode", + SerializedName = @"renewalMode", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Auto", "Manual")] + public string OfferDetailRenewalMode { get => _resourceBody.OfferDetailRenewalMode ?? null; set => _resourceBody.OfferDetailRenewalMode = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Plan Display Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Display Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Display Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// Workspace Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace Id in partner's system", + SerializedName = @"workspaceId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceId { get => _resourceBody.PartnerOrganizationPropertyWorkspaceId ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceId = value; } + + /// Workspace name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Workspace name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Workspace name in partner's system", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyWorkspaceName { get => _resourceBody.PartnerOrganizationPropertyWorkspaceName ?? null; set => _resourceBody.PartnerOrganizationPropertyWorkspaceName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserEmailAddress { get => _resourceBody.UserEmailAddress ?? null; set => _resourceBody.UserEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserFirstName { get => _resourceBody.UserFirstName ?? null; set => _resourceBody.UserFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserLastName { get => _resourceBody.UserLastName ?? null; set => _resourceBody.UserLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserPhoneNumber { get => _resourceBody.UserPhoneNumber ?? null; set => _resourceBody.UserPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Astro.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Astro.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserUpn { get => _resourceBody.UserUpn ?? null; set => _resourceBody.UserUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzAstroOrganization_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Cmdlets.UpdateAzAstroOrganization_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzAstroOrganization_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Astro.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParametersWithGetResult() + { + bool supportsSystemAssignedIdentity = (true == this.EnableSystemAssignedIdentity || null == this.EnableSystemAssignedIdentity && true == _resourceBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _resourceBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _resourceBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned"; + } + else + { + _resourceBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.OrganizationsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.OrganizationsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate); + } + 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.OrganizationsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.OrganizationsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzAstroOrganization_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceSubscriptionStatus"))) + { + this.MarketplaceSubscriptionStatus = (string)(this.MyInvocation?.BoundParameters["MarketplaceSubscriptionStatus"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserEmailAddress"))) + { + this.UserEmailAddress = (string)(this.MyInvocation?.BoundParameters["UserEmailAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceSubscriptionId"))) + { + this.MarketplaceSubscriptionId = (string)(this.MyInvocation?.BoundParameters["MarketplaceSubscriptionId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailRenewalMode"))) + { + this.OfferDetailRenewalMode = (string)(this.MyInvocation?.BoundParameters["OfferDetailRenewalMode"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserFirstName"))) + { + this.UserFirstName = (string)(this.MyInvocation?.BoundParameters["UserFirstName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserLastName"))) + { + this.UserLastName = (string)(this.MyInvocation?.BoundParameters["UserLastName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserUpn"))) + { + this.UserUpn = (string)(this.MyInvocation?.BoundParameters["UserUpn"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserPhoneNumber"))) + { + this.UserPhoneNumber = (string)(this.MyInvocation?.BoundParameters["UserPhoneNumber"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyOrganizationId"))) + { + this.PartnerOrganizationPropertyOrganizationId = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyOrganizationId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyWorkspaceId"))) + { + this.PartnerOrganizationPropertyWorkspaceId = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyWorkspaceId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyOrganizationName"))) + { + this.PartnerOrganizationPropertyOrganizationName = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyOrganizationName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PartnerOrganizationPropertyWorkspaceName"))) + { + this.PartnerOrganizationPropertyWorkspaceName = (string)(this.MyInvocation?.BoundParameters["PartnerOrganizationPropertyWorkspaceName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertyAadDomain"))) + { + this.SingleSignOnPropertyAadDomain = (string[])(this.MyInvocation?.BoundParameters["SingleSignOnPropertyAadDomain"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPublisherId"))) + { + this.OfferDetailPublisherId = (string)(this.MyInvocation?.BoundParameters["OfferDetailPublisherId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailOfferId"))) + { + this.OfferDetailOfferId = (string)(this.MyInvocation?.BoundParameters["OfferDetailOfferId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPlanId"))) + { + this.OfferDetailPlanId = (string)(this.MyInvocation?.BoundParameters["OfferDetailPlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailPlanName"))) + { + this.OfferDetailPlanName = (string)(this.MyInvocation?.BoundParameters["OfferDetailPlanName"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailTermUnit"))) + { + this.OfferDetailTermUnit = (string)(this.MyInvocation?.BoundParameters["OfferDetailTermUnit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("OfferDetailTermId"))) + { + this.OfferDetailTermId = (string)(this.MyInvocation?.BoundParameters["OfferDetailTermId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertySingleSignOnState"))) + { + this.SingleSignOnPropertySingleSignOnState = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertySingleSignOnState"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertyEnterpriseAppId"))) + { + this.SingleSignOnPropertyEnterpriseAppId = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertyEnterpriseAppId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("SingleSignOnPropertySingleSignOnUrl"))) + { + this.SingleSignOnPropertySingleSignOnUrl = (string)(this.MyInvocation?.BoundParameters["SingleSignOnPropertySingleSignOnUrl"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Astro.Models.IOrganizationResource + /// 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.Astro.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..fd20be26b41 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this cmdlet"); + } + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..d154112e19a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..1abcbb061eb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to a type + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..52dfcf1c848 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..75125420b93 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..2636f760fe8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..2b1944b7d0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..af0cae20bfa --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..9d7308f7e18 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..302e46ec15f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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.Astro.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..cd21c8a4e33 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.HasAllowEmptyArray.ToAllowEmptyArray()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..e18734a577f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.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.Astro.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: Astro cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.Astro.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.Astro.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = '{previewVersion}'"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule Sphere".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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..91ce242ed00 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + /*var loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + + + + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + sb.AppendLine(@"{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath)" + ); + sb.AppendLine($@" $TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@" $currentPath = $PSScriptRoot + while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent + } + . ($mockingPath | Select-Object -First 1).FullName +} +"); + + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..b0b78fa86a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..9d2bd7426a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..5aef4e3c8a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..655958ddeea --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..d42e3809d41 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"[{relatedLink}]({relatedLink}){Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..4054d64ad44 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..872b02e8a74 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + ExampleInfo.Description.ToDescriptionFormat()); ; + } + } + } + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://learn.microsoft.com/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Synopsis.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + public const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..c9ff8a16012 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..9fd00447677 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && !pg.Parameters.All(p => p.IsHidden())) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (codeEndIndex ?? 0)) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, output, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow && !p.IsHidden()).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..632f772621c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{Environment.NewLine}" : String.Empty; + } + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Astro.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText}{externalUrlsText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new[] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new[] { "
", "\r\n", "\n" }); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..a67d6d84126 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + + public string RootModuleName { get => @""; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + if (variantParamCountGroups.Length == 0) + { + variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + } + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public bool IsNotSuggestDefaultParameterSet { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + IsNotSuggestDefaultParameterSet = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public bool HasAllowEmptyArray { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + public PSArgumentCompleterAttribute PSArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}"; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines(); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[] { } : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => (!ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + public static PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(completerAttribute); + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..0426b7fcc78 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class ConstantAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..9186bbf7a8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..4d36566a499 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,105 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.TrimStart().StartsWith(GuidStart.TrimStart()))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..54f74e4187d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..bcbcdee354d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..7d65a3e956d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..530755c9dc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.Astro.AstronomerAstro Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..469a28003f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..e72a98ba5e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..7451a14b341 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..171dcc4a70c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..23fb7f5f471 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..2cbd7ca8b2c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..e0d3e69bc57 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..a4f5d76f9a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..66300f2dfc5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..466ca9f68f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..f672f039f56 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..a2c6b0b4a91 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..fa25eb6d08f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..5e29c0c9045 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..a8d4b8b443b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..7410afabaad --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..23d8723abb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..af14d09ab94 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..b2c05c24b23 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..e06be7c2c59 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..0e98c812877 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..c54151b3e1d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..06f9927cac3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..4e05c9aa560 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..c12dfc464c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..d46ba6440f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..6a16deb3cf8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..ca19a855b0d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.JsonSerializable.ToJson(dict, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..e70f1342fe4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..b99f429e8b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..81fdacaddc5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..9e347b74b7a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..1c983397797 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..eb97394326b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..252ffb2b190 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..e503ae38c00 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..7da77277273 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..699a21b9aa2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..913295ff3ce --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime +{ + using System; + + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..9f1a78a011e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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.Astro.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..746db4d40a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + public const string Progress = nameof(Progress); + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..5b8c7bb6350 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..83de7ee609f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Extensions.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..1bcd11a2821 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..7deb2a1722b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..0123d9f3379 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..8f3969629f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..c1e7fc1be95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..6b27872c192 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..fb2db9b3006 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..e818f4f8bbc --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..1b1086fc074 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..132f0a2183a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/ISendAsync.cs @@ -0,0 +1,413 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private const int DefaultMaxRetry = 3; + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..770b526b309 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..8c7827c40e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..cf51c759999 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..184f7066278 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..7f0b66e32e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..b44277d3281 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Astro.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..4c4be749b4d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..ac93d039eff --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..6496f8db0aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..4f4c6f71091 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..9793a76a796 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..7c43e6d2fe6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..b759b92e82e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..450840b561e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + internal XNodeArray(System.Collections.Generic.List values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..335190b5436 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..e08c7489f39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..e9aa10d5343 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..867c2c0331f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..4e69e1deb51 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..ba81f2fb5f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..cd33a78f568 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..16bd5a25463 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..3c5cf6e48b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..b413103dd9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..71ab2ba722b --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..e55b98ddb68 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..8f1aa7fce5c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..aec2504a3c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..af233b9fffb --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..44f805bfd9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..3682585f71c --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"), isBase64Request)) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..bb4820c7ed1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.Astro.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..a08a2e50172 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..ad92cf8c623 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..3478c5546ff --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..ac9ba3d270d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..1584845fb66 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..12d81e6acfd --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/SerializationMode.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..1c730e74cdd --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.List SelectToList(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }.ToList(); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0].ToList(); // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result; + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..5fac7b8c717 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.Astro.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.Astro.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Astro.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // see if there is an error block in the body + json = json?.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..82294bc51de --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..360689bce5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/how-to.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/how-to.md new file mode 100644 index 00000000000..0ea50d78223 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.Astro`. + +## Building `Az.Astro` +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.Astro` +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.Astro` +To pack `Az.Astro` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Astro`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Astro.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Astro.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Astro`. + - `-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.Astro` 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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/Az.Astro.internal.psm1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/Az.Astro.internal.psm1 new file mode 100644 index 00000000000..2f1bbf8350d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/Az.Astro.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Astro.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/README.md new file mode 100644 index 00000000000..40216e31943 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/internal/README.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.Astro.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.Astro`. Instead, this sub-module is imported by the `..\custom\Az.Astro.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.Astro.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.Astro`. diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/license.txt b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/license.txt @@ -0,0 +1,227 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + + +The software includes the AutoMapper library ("AutoMapper"). The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Provided for Informational Purposes Only + +AutoMapper + +The MIT License (MIT) +Copyright (c) 2010 Jimmy Bogard + + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + +*************** + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/resources/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/run-module.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/run-module.ps1 new file mode 100644 index 00000000000..eb01ee87047 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Astro.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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test-module.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test-module.ps1 new file mode 100644 index 00000000000..e4c24898ed6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) +{ + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Astro.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/README.md new file mode 100644 index 00000000000..cdaf3a995a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/README.md @@ -0,0 +1,438 @@ + +# Az.Resources.TestSupport +This directory contains the PowerShell module for the Resources service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Resources.TestSupport`, 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
`npm install -g 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` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +> Values +``` yaml +azure: true +powershell: true +branch: master +repo: https://github.com/Azure/azure-rest-api-specs/blob/$(branch) +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + copyright: Microsoft Corporation. All rights reserved. + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell +``` + +> Names +``` yaml +prefix: Az +``` + +> Folders +``` yaml +clear-output-folder: true +``` + +``` yaml +input-file: + - $(repo)/specification/resources/resource-manager/Microsoft.Resources/stable/2018-05-01/resources.json +module-name: Az.Resources.TestSupport +namespace: Microsoft.Azure.PowerShell.Cmdlets.Resources + +subject-prefix: '' +module-version: 0.0.1 +title: Resources + +directive: + - remove-operation: Deployments_CreateOrUpdateAtSubscriptionScope + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - from: swagger-document + where: $..parameters[?(@.name=='$filter')] + transform: $['x-ms-skip-url-encoding'] = true + - from: swagger-document + where: $..[?( /Resources_(CreateOrUpdate|Update|Delete|Get|GetById|CheckExistence|CheckExistenceById)/g.exec(@.operationId))] + transform: "$.parameters = $.parameters.map( each => { each.name = each.name === 'api-version' ? 'explicit-api-version' : each.name; return each; } );" + - from: source-file-csharp + where: $ + transform: $ = $.replace(/explicit-api-version/g, 'api-version'); + - where: + parameter-name: ExplicitApiVersion + set: + parameter-name: ApiVersion + - from: source-file-csharp + where: $ + transform: > + $ = $.replace(/result.OdataNextLink/g,'nextLink' ); + return $.replace( /(^\s*)(if\s*\(\s*nextLink\s*!=\s*null\s*\))/gm, '$1var nextLink = Module.Instance.FixNextLink(responseMessage, result.OdataNextLink);\n$1$2' ); + - from: swagger-document + where: + - $..DeploymentProperties.properties.template + - $..DeploymentProperties.properties.parameters + - $..ResourceGroupExportResult.properties.template + - $..PolicyDefinitionProperties.properties.policyRule + transform: $.additionalProperties = true; + - where: + verb: Set + subject: Resource + remove: true + - where: + verb: Set + subject: Deployment + remove: true + - where: + subject: Resource + parameter-name: GroupName + set: + parameter-name: ResourceGroupName + clear-alias: true + - where: + subject: Resource + parameter-name: Id + set: + parameter-name: ResourceId + clear-alias: true + - where: + subject: Resource + parameter-name: Type + set: + parameter-name: ResourceType + clear-alias: true + - where: + subject: Appliance* + remove: true + - where: + verb: Test + subject: CheckNameAvailability + set: + subject: NameAvailability + - where: + verb: Export + subject: ResourceGroupTemplate + set: + subject: ResourceGroup + alias: Export-AzResourceGroupTemplate + - where: + parameter-name: Filter + set: + alias: ODataQuery + - where: + verb: Test + subject: ResourceGroupExistence + set: + subject: ResourceGroup + alias: Test-AzResourceGroupExistence + - where: + verb: Export + subject: DeploymentTemplate + set: + alias: [Save-AzDeploymentTemplate, Save-AzResourceGroupDeploymentTemplate] + - where: + subject: Deployment + set: + alias: ${verb}-AzResourceGroupDeployment + - where: + verb: Get + subject: DeploymentOperation + set: + alias: Get-AzResourceGroupDeploymentOperation + - where: + verb: New + subject: Deployment + variant: Create.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + hide: true + - where: + verb: Test + subject: Deployment + variant: Validate.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + parameter-name: DebugSettingDetailLevel + set: + parameter-name: DeploymentDebugLogLevel + - where: + subject: Provider + set: + subject: ResourceProvider + - where: + subject: ProviderFeature|ResourceProvider|ResourceLock + parameter-name: ResourceProviderNamespace + set: + alias: ProviderNamespace + - where: + verb: Update + subject: ResourceGroup + parameter-name: Name + clear-alias: true + - where: + parameter-name: UpnOrObjectId + set: + alias: ['UserPrincipalName', 'Upn', 'ObjectId'] + - where: + subject: Deployment + variant: (.*)Expanded(.*) + parameter-name: Parameter + set: + parameter-name: DeploymentParameter + # Format output + - where: + model-name: GenericResource + set: + format-table: + properties: + - Name + - ResourceGroupName + - Type + - Location + labels: + Type: ResourceType + - where: + model-name: ResourceGroup + set: + format-table: + properties: + - Name + - Location + - ProvisioningState + - where: + model-name: DeploymentExtended + set: + format-table: + properties: + - Name + - ProvisioningState + - Timestamp + - Mode + - where: + model-name: PolicyAssignment + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicyDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicySetDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: Provider + set: + format-table: + properties: + - Namespace + - RegistrationState + - where: + model-name: ProviderResourceType + set: + format-table: + properties: + - ResourceType + - Location + - ApiVersion + - where: + model-name: FeatureResult + set: + format-table: + properties: + - Name + - State + - where: + model-name: TagDetails + set: + format-table: + properties: + - TagName + - CountValue + - where: + model-name: Application + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppId + - Homepage + - AvailableToOtherTenant + - where: + model-name: KeyCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - Type + - where: + model-name: PasswordCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - where: + model-name: User + set: + format-table: + properties: + - PrincipalName + - DisplayName + - ObjectId + - Type + - where: + model-name: AdGroup + set: + format-table: + properties: + - DisplayName + - Mail + - ObjectId + - SecurityEnabled + - where: + model-name: ServicePrincipal + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppDisplayName + - AppId + - where: + model-name: Location + set: + format-table: + properties: + - Name + - DisplayName + - where: + model-name: ManagementLockObject + set: + format-table: + properties: + - Name + - Level + - ResourceId + - where: + model-name: RoleAssignment + set: + format-table: + properties: + - DisplayName + - ObjectId + - ObjectType + - RoleDefinitionName + - Scope + - where: + model-name: RoleDefinition + set: + format-table: + properties: + - RoleName + - Name + - Action +# To remove cmdlets not used in the test frame + - where: + subject: Operation + remove: true + - where: + subject: Deployment + variant: (.*)1|Cancel(.*)|Validate(.*)|Export(.*)|List(.*)|Delete(.*)|Check(.*)|Calculate(.*) + remove: true + - where: + subject: ResourceProvider + variant: Register(.*)|Unregister(.*)|Get(.*) + remove: true + - where: + subject: ResourceGroup + variant: List(.*)|Update(.*)|Export(.*)|Move(.*) + remove: true + - where: + subject: Resource + remove: true + - where: + subject: Tag|TagValue + remove: true + - where: + subject: DeploymentOperation + remove: true + - where: + subject: DeploymentTemplate + remove: true + - where: + subject: Calculate(.*) + remove: true + - where: + subject: ResourceExistence + remove: true + - where: + subject: ResourceMoveResource + remove: true + - where: + subject: DeploymentExistence + remove: true +``` diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/custom/New-AzDeployment.ps1 @@ -0,0 +1,231 @@ +function New-AzDeployment { + [OutputType('Microsoft.Azure.PowerShell.Cmdlets.Resources.Models.IDeploymentExtended')] + [CmdletBinding(DefaultParameterSetName='CreateWithTemplateFileParameterFile', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Description('You can provide the template and parameters directly in the request or link to JSON files.')] + param( + [Parameter(HelpMessage='The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name.')] + [Alias('DeploymentName')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='deploymentName', Required, PossibleTypes=([System.String]), Description='The name of the deployment.')] + [System.String] + # The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name. + ${Name}, + + [Parameter(Mandatory, HelpMessage='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='subscriptionId', Required, PossibleTypes=([System.String]), Description='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='resourceGroupName', Required, PossibleTypes=([System.String]), Description='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [System.String] + # The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [System.String] + # Local path to the JSON template file. + ${TemplateFile}, + + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [System.String] + # The string representation of the JSON template. + ${TemplateJson}, + + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the JSON template. + ${TemplateObject}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [System.String] + # Local path to the parameter JSON template file. + ${TemplateParameterFile}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [System.String] + # The string representation of the parameter JSON template. + ${TemplateParameterJson}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the parameter JSON template. + ${TemplateParameterObject}, + + [Parameter(Mandatory, HelpMessage='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode])] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='mode', Required, PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode]), Description='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode] + # The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. + ${Mode}, + + [Parameter(HelpMessage='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='detailLevel', PossibleTypes=([System.String]), Description='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [System.String] + # Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations. + ${DeploymentDebugLogLevel}, + + [Parameter(HelpMessage='The location to store the deployment data.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='location', PossibleTypes=([System.String]), Description='The location to store the deployment data.')] + [System.String] + # The location to store the deployment data. + ${Location}, + + [Parameter(HelpMessage='The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(HelpMessage='Run the command asynchronously')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait} + + ) + + process { + if ($PSBoundParameters.ContainsKey("TemplateFile")) + { + if (!(Test-Path -Path $TemplateFile)) + { + throw "Unable to find template file '$TemplateFile'." + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (Get-Item -Path $TemplateFile).BaseName + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + $TemplateJson = [System.IO.File]::ReadAllText($TemplateFile) + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateJson")) + { + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateObject")) + { + $TemplateJson = ConvertTo-Json -InputObject $TemplateObject + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateObject") + } + + if ($PSBoundParameters.ContainsKey("TemplateParameterFile")) + { + if (!(Test-Path -Path $TemplateParameterFile)) + { + throw "Unable to find template parameter file '$TemplateParameterFile'." + } + + $ParameterJson = [System.IO.File]::ReadAllText($TemplateParameterFile) + $ParameterObject = ConvertFrom-Json -InputObject $ParameterJson + $ParameterHashtable = @{} + $ParameterObject.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + $ParameterHashtable.Remove("`$schema") + $ParameterHashtable.Remove("contentVersion") + $NestedValues = $ParameterHashtable.parameters + if ($null -ne $NestedValues) + { + $ParameterHashtable.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + } + + $ParameterJson = ConvertTo-Json -InputObject $ParameterHashtable + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $ParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterJson")) + { + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterObject")) + { + $TemplateParameterObject.Remove("`$schema") + $TemplateParameterObject.Remove("contentVersion") + $NestedValues = $TemplateParameterObject.parameters + if ($null -ne $NestedValues) + { + $TemplateParameterObject.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $TemplateParameterObject[$_.Name] = $_.Value } + } + + $TemplateParameterJson = ConvertTo-Json -InputObject $TemplateParameterObject + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterObject") + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (New-Guid).Guid + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + if ($PSBoundParameters.ContainsKey("ResourceGroupName")) + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + else + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Resources` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overriden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Resources` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/how-to.md @@ -0,0 +1,60 @@ +# How-To +This document describes how to develop for `Az.Resources`. + +## Building `Az.Resources` +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.Resources` +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.Resources` +To pack `Az.Resources` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Resources`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Resources.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Resources.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Resources`. + - `-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.Resources` 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`. +- `generate-portal-ux.ps1` + - Generates a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +- `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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/license.txt @@ -0,0 +1,203 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md @@ -0,0 +1,598 @@ +### AzADApplication [Get, New, Remove, Update] `IApplication, Boolean` + - TenantId `String` + - ObjectId `String` + - IncludeDeleted `SwitchParameter` + - InputObject `IResourcesIdentity` + - HardDelete `SwitchParameter` + - Filter `String` + - IdentifierUri `String` + - DisplayNameStartWith `String` + - DisplayName `String` + - ApplicationId `String` + - AllowGuestsSignIn `SwitchParameter` + - AllowPassthroughUser `SwitchParameter` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenants `SwitchParameter` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes` + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `SwitchParameter` + - Oauth2AllowUrlPathMatching `SwitchParameter` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `SwitchParameter` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `SwitchParameter` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + - Parameter `IApplicationCreateParameters` + - PassThru `SwitchParameter` + - AvailableToOtherTenant `SwitchParameter` + +### AzADApplicationOwner [Add, Get, Remove] `Boolean, IDirectoryObject` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADDeletedApplication [Restore] `IApplication` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + +### AzADGroup [Get, New, Remove] `IAdGroup, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayNameStartsWith `String` + - DisplayName `String` + - AdditionalProperties `Hashtable` + - MailNickname `String` + - Parameter `IGroupCreateParameters` + - PassThru `SwitchParameter` + +### AzADGroupMember [Add, Get, Remove, Test] `Boolean, IDirectoryObject, SwitchParameter` + - GroupObjectId `String` + - TenantId `String` + - MemberObjectId `String[]` + - MemberUserPrincipalName `String[]` + - GroupObject `IAdGroup` + - GroupDisplayName `String` + - InputObject `IResourcesIdentity` + - ObjectId `String` + - ShowOwner `SwitchParameter` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IGroupAddMemberParameters` + - DisplayName `String` + - GroupId `String` + - MemberId `String` + +### AzADGroupMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IGroupGetMemberGroupsParameters` + +### AzADGroupOwner [Add, Remove] `Boolean` + - ObjectId `String` + - TenantId `String` + - GroupObjectId `String` + - MemberObjectId `String[]` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADObject [Get] `IDirectoryObject` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - IncludeDirectoryObjectReference `SwitchParameter` + - ObjectId `String[]` + - Type `String[]` + - Parameter `IGetObjectsParameters` + +### AzADServicePrincipal [Get, New, Remove, Update] `IServicePrincipal, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ApplicationObject `IApplication` + - ServicePrincipalName `String` + - DisplayNameBeginsWith `String` + - DisplayName `String` + - ApplicationId `String` + - AccountEnabled `SwitchParameter` + - AppId `String` + - AppRoleAssignmentRequired `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + - Parameter `IServicePrincipalCreateParameters` + - PassThru `SwitchParameter` + +### AzADServicePrincipalOwner [Get] `IDirectoryObject` + - ObjectId `String` + - TenantId `String` + +### AzADUser [Get, New, Remove, Update] `IUser, Boolean` + - TenantId `String` + - UpnOrObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayName `String` + - StartsWith `String` + - Mail `String` + - MailNickname `String` + - Parameter `IUserCreateParameters` + - AccountEnabled `SwitchParameter` + - GivenName `String` + - ImmutableId `String` + - PasswordProfile `IPasswordProfile` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType` + - PassThru `SwitchParameter` + - EnableAccount `SwitchParameter` + +### AzADUserMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IUserGetMemberGroupsParameters` + +### AzApplicationKeyCredentials [Get, Update] `IKeyCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IKeyCredentialsUpdateParameters` + - Value `IKeyCredential[]` + +### AzApplicationPasswordCredentials [Get, Update] `IPasswordCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IPasswordCredentialsUpdateParameters` + - Value `IPasswordCredential[]` + +### AzAuthorizationOperation [Get] `IOperation` + +### AzClassicAdministrator [Get] `IClassicAdministrator` + - SubscriptionId `String[]` + +### AzDenyAssignment [Get] `IDenyAssignment` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - Filter `String` + +### AzDeployment [Get, New, Remove, Set, Stop, Test] `IDeploymentExtended, Boolean, IDeploymentValidateResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Top `Int32` + - Parameter `IDeployment` + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - PassThru `SwitchParameter` + +### AzDeploymentExistence [Test] `Boolean` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDeploymentOperation [Get] `IDeploymentOperation` + - DeploymentName `String` + - SubscriptionId `String[]` + - ResourceGroupName `String` + - OperationId `String` + - DeploymentObject `IDeploymentExtended` + - InputObject `IResourcesIdentity` + - Top `Int32` + +### AzDeploymentTemplate [Export] `IDeploymentExportResultTemplate` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDomain [Get] `IDomain` + - TenantId `String` + - Name `String` + - InputObject `IResourcesIdentity` + - Filter `String` + +### AzElevateGlobalAdministratorAccess [Invoke] `Boolean` + +### AzEntity [Get] `IEntityInfo` + - Filter `String` + - GroupName `String` + - Search `String` + - Select `String` + - Skip `Int32` + - Skiptoken `String` + - Top `Int32` + - View `String` + - CacheControl `String` + +### AzManagedApplication [Get, New, Remove, Set, Update] `IApplication, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplication` + - ApplicationDefinitionId `String` + - IdentityType `ResourceIdentityType` + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagedApplicationDefinition [Get, New, Remove, Set] `IApplicationDefinition, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplicationDefinition` + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - PackageFileUri `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagementGroup [Get, New, Remove, Set, Update] `IManagementGroup, IManagementGroupInfo, Boolean` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Expand `String` + - Filter `String` + - Recurse `SwitchParameter` + - CacheControl `String` + - DisplayName `String` + - Name `String` + - ParentId `String` + - CreateManagementGroupRequest `ICreateManagementGroupRequest` + - PatchGroupRequest `IPatchManagementGroupRequest` + +### AzManagementGroupDescendant [Get] `IDescendantInfo` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Top `Int32` + +### AzManagementGroupSubscription [New, Remove] `Boolean` + - GroupId `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - CacheControl `String` + +### AzManagementLock [Get, New, Remove, Set] `IManagementLockObject, Boolean` + - SubscriptionId `String[]` + - LockName `String` + - ResourceGroupName `String` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Level `LockLevel` + - Note `String` + - Owner `IManagementLockOwner[]` + - Parameter `IManagementLockObject` + +### AzNameAvailability [Test] `ICheckNameAvailabilityResult` + - Name `String` + - Type `Type` + - CheckNameAvailabilityRequest `ICheckNameAvailabilityRequest` + +### AzOAuth2PermissionGrant [Get, New, Remove] `IOAuth2PermissionGrant, Boolean` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ClientId `String` + - ConsentType `ConsentType` + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + - Body `IOAuth2PermissionGrant` + +### AzPermission [Get] `IPermission` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + +### AzPolicyAssignment [Get, New, Remove] `IPolicyAssignment` + - Id `String` + - Name `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - PolicyDefinitionId `String` + - IncludeDescendent `SwitchParameter` + - Filter `String` + - Parameter `IPolicyAssignment` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - SkuName `String` + - SkuTier `String` + - PropertiesScope `String` + +### AzPolicyDefinition [Get, New, Remove, Set] `IPolicyDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicyDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzPolicySetDefinition [Get, New, Remove, Set] `IPolicySetDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicySetDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzProviderFeature [Get, Register] `IFeatureResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + +### AzProviderOperationsMetadata [Get] `IProviderOperationsMetadata` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + +### AzResource [Get, Move, New, Remove, Set, Test, Update] `IGenericResource, Boolean` + - ResourceId `String` + - Name `String` + - ParentResourcePath `String` + - ProviderNamespace `String` + - ResourceGroupName `String` + - ResourceType `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - SourceResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - Expand `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Filter `String` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + - IdentityType `ResourceIdentityType` + - IdentityUserAssignedIdentity `Hashtable` + - Kind `String` + - Location `String` + - ManagedBy `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + +### AzResourceGroup [Export, Get, New, Remove, Set, Test, Update] `IResourceGroupExportResult, IResourceGroup, Boolean` + - ResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Id `String` + - Filter `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Option `String` + - Resource `String[]` + - Parameter `IExportTemplateRequest` + - Location `String` + - ManagedBy `String` + +### AzResourceLink [Get, New, Remove, Set] `IResourceLink, Boolean` + - ResourceId `String` + - InputObject `IResourcesIdentity` + - SubscriptionId `String[]` + - Scope `String` + - FilterById `String` + - FilterByScope `Filter` + - Note `String` + - TargetId `String` + - Parameter `IResourceLink` + +### AzResourceMove [Test] `Boolean` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + +### AzResourceProvider [Get, Register, Unregister] `IProvider` + - SubscriptionId `String[]` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + - Top `Int32` + +### AzResourceProviderOperationDetail [Get] `IResourceProviderOperationDefinition` + - ResourceProviderNamespace `String` + +### AzRoleAssignment [Get, New, Remove] `IRoleAssignment` + - Id `String` + - Name `String` + - Scope `String` + - RoleId `String` + - InputObject `IResourcesIdentity` + - ParentResourceId `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - ExpandPrincipalGroups `String` + - ServicePrincipalName `String` + - SignInName `String` + - Filter `String` + - CanDelegate `SwitchParameter` + - PrincipalId `String` + - RoleDefinitionId `String` + - Parameter `IRoleAssignmentCreateParameters` + - PrincipalType `PrincipalType` + +### AzRoleDefinition [Get, New, Remove, Set] `IRoleDefinition` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Custom `SwitchParameter` + - Filter `String` + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - RoleDefinition `IRoleDefinition` + +### AzSubscriptionLocation [Get] `ILocation` + - SubscriptionId `String[]` + +### AzTag [Get, New, Remove] `ITagDetails, Boolean` + - SubscriptionId `String[]` + - Name `String` + - Value `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + +### AzTenantBackfill [Start] `ITenantBackfillStatusResult` + +### AzTenantBackfillStatus [Invoke] `ITenantBackfillStatusResult` + diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/ModelSurface.md @@ -0,0 +1,1645 @@ +### AddOwnerParameters \ [Api16] + - Url `String` + +### AdGroup \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - Mail `String` + - MailEnabled `Boolean?` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - SecurityEnabled `Boolean?` + +### AliasPathType [Api20180501] + - ApiVersion `String[]` + - Path `String` + +### AliasType [Api20180501] + - Name `String` + - Path `IAliasPathType[]` + +### Appliance [Api20160901Preview] + - DefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceArtifact [Api20160901Preview] + - Name `String` + - Type `ApplianceArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplianceDefinition [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplianceDefinitionListResult [Api20160901Preview] + - NextLink `String` + - Value `IApplianceDefinition[]` + +### ApplianceDefinitionProperties [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - PackageFileUri `String` + +### ApplianceListResult [Api20160901Preview] + - NextLink `String` + - Value `IAppliance[]` + +### AppliancePatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceProperties [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### AppliancePropertiesPatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplianceProviderAuthorization [Api20160901Preview] + - PrincipalId `String` + - RoleDefinitionId `String` + +### Application \ [Api16, Api20170901, Api20180601] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppId `String` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DefinitionId `String` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - Id `String` + - IdentifierUri `String[]` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - Kind `String` + - KnownClientApplication `String[]` + - Location `String` + - LogoutUrl `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - ObjectId `String` + - ObjectType `String` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - PasswordCredentials `IPasswordCredential[]` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - ProvisioningState `String` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + - WwwHomepage `String` + +### ApplicationArtifact [Api20170901] + - Name `String` + - Type `ApplicationArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplicationBase [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationCreateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationDefinition [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplicationDefinitionListResult [Api20180601] + - NextLink `String` + - Value `IApplicationDefinition[]` + +### ApplicationDefinitionProperties [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IsEnabled `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - PackageFileUri `String` + +### ApplicationListResult [Api16, Api20180601] + - NextLink `String` + - OdataNextLink `String` + - Value `IApplication[]` + +### ApplicationPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplicationProperties [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationPropertiesPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationProviderAuthorization [Api20170901] + - PrincipalId `String` + - RoleDefinitionId `String` + +### ApplicationUpdateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### AppRole [Api16] + - AllowedMemberType `String[]` + - Description `String` + - DisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Value `String` + +### BasicDependency [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### CheckGroupMembershipParameters \ [Api16] + - GroupId `String` + - MemberId `String` + +### CheckGroupMembershipResult \ [Api16] + - Value `Boolean?` + +### CheckNameAvailabilityRequest [Api20180301Preview] + - Name `String` + - Type `Type?` **{ProvidersMicrosoftManagementGroups}** + +### CheckNameAvailabilityResult [Api20180301Preview] + - Message `String` + - NameAvailable `Boolean?` + - Reason `Reason?` **{AlreadyExists, Invalid}** + +### ClassicAdministrator [Api20150701] + - EmailAddress `String` + - Id `String` + - Name `String` + - Role `String` + - Type `String` + +### ClassicAdministratorListResult [Api20150701] + - NextLink `String` + - Value `IClassicAdministrator[]` + +### ClassicAdministratorProperties [Api20150701] + - EmailAddress `String` + - Role `String` + +### ComponentsSchemasIdentityPropertiesUserassignedidentitiesAdditionalproperties [Api20180501] + - ClientId `String` + - PrincipalId `String` + +### CreateManagementGroupChildInfo [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### CreateManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### CreateManagementGroupProperties [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### CreateManagementGroupRequest [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### CreateParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### DebugSetting [Api20180501] + - DetailLevel `String` + +### DenyAssignment [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - Id `String` + - IsSystemProtected `Boolean?` + - Name `String` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + - Type `String` + +### DenyAssignmentListResult [Api20180701Preview] + - NextLink `String` + - Value `IDenyAssignment[]` + +### DenyAssignmentPermission [Api20180701Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### DenyAssignmentProperties [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - IsSystemProtected `Boolean?` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + +### Dependency [Api20180501] + - DependsOn `IBasicDependency[]` + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### Deployment [Api20180501] + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentExportResult [Api20180501] + - Template `IDeploymentExportResultTemplate` + +### DeploymentExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Id `String` + - Location `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - Name `String` + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + - Type `String` + +### DeploymentListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentExtended[]` + +### DeploymentOperation [Api20180501] + - Id `String` + - OperationId `String` + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationProperties [Api20180501] + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationsListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentOperation[]` + +### DeploymentProperties [Api20180501] + - DebugSettingDetailLevel `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentPropertiesExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentValidateResult [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DescendantInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - ParentId `String` + - Type `String` + +### DescendantInfoProperties [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### DescendantListResult [Api20180301Preview] + - NextLink `String` + - Value `IDescendantInfo[]` + +### DescendantParentGroupInfo [Api20180301Preview] + - Id `String` + +### DirectoryObject \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - ObjectId `String` + - ObjectType `String` + +### DirectoryObjectListResult [Api16] + - OdataNextLink `String` + - Value `IDirectoryObject[]` + +### Domain \ [Api16] + - AuthenticationType `String` + - IsDefault `Boolean?` + - IsVerified `Boolean?` + - Name `String` + +### DomainListResult [Api16] + - Value `IDomain[]` + +### EntityInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - InheritedPermission `String` + - Name `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + - Type `String` + +### EntityInfoProperties [Api20180301Preview] + - DisplayName `String` + - InheritedPermission `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + +### EntityListResult [Api20180301Preview] + - Count `Int32?` + - NextLink `String` + - Value `IEntityInfo[]` + +### EntityParentGroupInfo [Api20180301Preview] + - Id `String` + +### ErrorDetails [Api20180301Preview] + - Code `String` + - Detail `String` + - Message `String` + +### ErrorMessage [Api16] + - Message `String` + +### ErrorResponse [Api20160901Preview, Api20180301Preview] + - ErrorCode `String` + - ErrorDetail `String` + - ErrorMessage `String` + - HttpStatus `String` + +### ExportTemplateRequest [Api20180501] + - Option `String` + - Resource `String[]` + +### FeatureOperationsListResult [Api20151201] + - NextLink `String` + - Value `IFeatureResult[]` + +### FeatureProperties [Api20151201] + - State `String` + +### FeatureResult [Api20151201] + - Id `String` + - Name `String` + - State `String` + - Type `String` + +### GenericResource [Api20160901Preview, Api20180501] + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IdentityUserAssignedIdentity `IIdentityUserAssignedIdentities ` + - Kind `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### GetObjectsParameters \ [Api16] + - IncludeDirectoryObjectReference `Boolean?` + - ObjectId `String[]` + - Type `String[]` + +### GraphError [Api16] + - ErrorMessageValueMessage `String` + - OdataErrorCode `String` + +### GroupAddMemberParameters \ [Api16] + - Url `String` + +### GroupCreateParameters \ [Api16] + - DisplayName `String` + - MailEnabled `Boolean` + - MailNickname `String` + - SecurityEnabled `Boolean` + +### GroupGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### GroupGetMemberGroupsResult [Api16] + - Value `String[]` + +### GroupListResult [Api16] + - OdataNextLink `String` + - Value `IAdGroup[]` + +### HttpMessage [Api20180501] + - Content `IHttpMessageContent` + +### Identity [Api20160901Preview, Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - UserAssignedIdentity `IIdentityUserAssignedIdentities ` + +### Identity1 [Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + +### InformationalUrl [Api16] + - Marketing `String` + - Privacy `String` + - Support `String` + - TermsOfService `String` + +### KeyCredential \ [Api16] + - CustomKeyIdentifier `String` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Type `String` + - Usage `String` + - Value `String` + +### KeyCredentialListResult [Api16] + - Value `IKeyCredential[]` + +### KeyCredentialsUpdateParameters [Api16] + - Value `IKeyCredential[]` + +### Location [Api20160601] + - DisplayName `String` + - Id `String` + - Latitude `String` + - Longitude `String` + - Name `String` + - SubscriptionId `String` + +### LocationListResult [Api20160601] + - Value `ILocation[]` + +### ManagementGroup [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### ManagementGroupChildInfo [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### ManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### ManagementGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - TenantId `String` + - Type `String` + +### ManagementGroupInfoProperties [Api20180301Preview] + - DisplayName `String` + - TenantId `String` + +### ManagementGroupListResult [Api20180301Preview] + - NextLink `String` + - Value `IManagementGroupInfo[]` + +### ManagementGroupProperties [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### ManagementLockListResult [Api20160901] + - NextLink `String` + - Value `IManagementLockObject[]` + +### ManagementLockObject [Api20160901] + - Id `String` + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Name `String` + - Note `String` + - Owner `IManagementLockOwner[]` + - Type `String` + +### ManagementLockOwner [Api20160901] + - ApplicationId `String` + +### ManagementLockProperties [Api20160901] + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Note `String` + - Owner `IManagementLockOwner[]` + +### OAuth2Permission [Api16] + - AdminConsentDescription `String` + - AdminConsentDisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Type `String` + - UserConsentDescription `String` + - UserConsentDisplayName `String` + - Value `String` + +### OAuth2PermissionGrant [Api16] + - ClientId `String` + - ConsentType `ConsentType?` **{AllPrincipals, Principal}** + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + +### OAuth2PermissionGrantListResult [Api16] + - OdataNextLink `String` + - Value `IOAuth2PermissionGrant[]` + +### OdataError [Api16] + - Code `String` + - ErrorMessageValueMessage `String` + +### OnErrorDeployment [Api20180501] + - DeploymentName `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### OnErrorDeploymentExtended [Api20180501] + - DeploymentName `String` + - ProvisioningState `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### Operation [Api20151201, Api20180301Preview] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayResource `String` + - Name `String` + +### OperationDisplay [Api20151201] + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationDisplayProperties [Api20180301Preview] + - Description `String` + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationListResult [Api20151201, Api20180301Preview] + - NextLink `String` + - Value `IOperation[]` + +### OperationResults [Api20180301Preview] + - Id `String` + - Name `String` + - ProvisioningState `String` + - Type `String` + +### OperationResultsProperties [Api20180301Preview] + - ProvisioningState `String` + +### OptionalClaim [Api16] + - AdditionalProperty `IOptionalClaimAdditionalProperties` + - Essential `Boolean?` + - Name `String` + - Source `String` + +### OptionalClaims [Api16] + - AccessToken `IOptionalClaim[]` + - IdToken `IOptionalClaim[]` + - SamlToken `IOptionalClaim[]` + +### ParametersLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### ParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### PasswordCredential \ [Api16] + - CustomKeyIdentifier `Byte[]` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Value `String` + +### PasswordCredentialListResult [Api16] + - Value `IPasswordCredential[]` + +### PasswordCredentialsUpdateParameters [Api16] + - Value `IPasswordCredential[]` + +### PasswordProfile \ [Api16] + - ForceChangePasswordNextLogin `Boolean?` + - Password `String` + +### PatchManagementGroupRequest [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### Permission [Api20150701, Api201801Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### PermissionGetResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IPermission[]` + +### Plan [Api20160901Preview, Api20180501] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PlanPatchable [Api20160901Preview] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PolicyAssignment [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - Name `String` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + - SkuName `String` + - SkuTier `String` + - Type `String` + +### PolicyAssignmentListResult [Api20151101, Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyAssignment[]` + +### PolicyAssignmentProperties [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + +### PolicyDefinition [Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Name `String` + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Property `IPolicyDefinitionProperties` + - Type `String` + +### PolicyDefinitionListResult [Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyDefinition[]` + +### PolicyDefinitionProperties [Api20161201] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicyDefinitionReference [Api20180501] + - Parameter `IPolicyDefinitionReferenceParameters` + - PolicyDefinitionId `String` + +### PolicySetDefinition [Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Name `String` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Type `String` + +### PolicySetDefinitionListResult [Api20180501] + - NextLink `String` + - Value `IPolicySetDefinition[]` + +### PolicySetDefinitionProperties [Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicySku [Api20180501] + - Name `String` + - Tier `String` + +### PreAuthorizedApplication [Api16] + - AppId `String` + - Extension `IPreAuthorizedApplicationExtension[]` + - Permission `IPreAuthorizedApplicationPermission[]` + +### PreAuthorizedApplicationExtension [Api16] + - Condition `String[]` + +### PreAuthorizedApplicationPermission [Api16] + - AccessGrant `String[]` + - DirectAccessGrant `Boolean?` + +### Principal [Api20180701Preview] + - Id `String` + - Type `String` + +### Provider [Api20180501] + - Id `String` + - Namespace `String` + - RegistrationState `String` + - ResourceType `IProviderResourceType[]` + +### ProviderListResult [Api20180501] + - NextLink `String` + - Value `IProvider[]` + +### ProviderOperation [Api20150701, Api201801Preview] + - Description `String` + - DisplayName `String` + - IsDataAction `Boolean?` + - Name `String` + - Origin `String` + - Property `IProviderOperationProperties` + +### ProviderOperationsMetadata [Api20150701, Api201801Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - Operation `IProviderOperation[]` + - ResourceType `IResourceType[]` + - Type `String` + +### ProviderOperationsMetadataListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IProviderOperationsMetadata[]` + +### ProviderResourceType [Api20180501] + - Alias `IAliasType[]` + - ApiVersion `String[]` + - Location `String[]` + - Property `IProviderResourceTypeProperties ` + - ResourceType `String` + +### RequiredResourceAccess \ [Api16] + - ResourceAccess `IResourceAccess[]` + - ResourceAppId `String` + +### Resource [Api20160901Preview] + - Id `String` + - Location `String` + - Name `String` + - Tag `IResourceTags ` + - Type `String` + +### ResourceAccess \ [Api16] + - Id `String` + - Type `String` + +### ResourceGroup [Api20180501] + - Id `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupTags ` + - Type `String` + +### ResourceGroupExportResult [Api20180501] + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Template `IResourceGroupExportResultTemplate` + +### ResourceGroupListResult [Api20180501] + - NextLink `String` + - Value `IResourceGroup[]` + +### ResourceGroupPatchable [Api20180501] + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupPatchableTags ` + +### ResourceGroupProperties [Api20180501] + - ProvisioningState `String` + +### ResourceLink [Api20160901] + - Id `String` + - Name `String` + - Note `String` + - SourceId `String` + - TargetId `String` + - Type `IResourceLinkType` + +### ResourceLinkProperties [Api20160901] + - Note `String` + - SourceId `String` + - TargetId `String` + +### ResourceLinkResult [Api20160901] + - NextLink `String` + - Value `IResourceLink[]` + +### ResourceListResult [Api20180501] + - NextLink `String` + - Value `IGenericResource[]` + +### ResourceManagementErrorWithDetails [Api20180501] + - Code `String` + - Detail `IResourceManagementErrorWithDetails[]` + - Message `String` + - Target `String` + +### ResourceProviderOperationDefinition [Api20151101] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayPublisher `String` + - DisplayResource `String` + - Name `String` + +### ResourceProviderOperationDetailListResult [Api20151101] + - NextLink `String` + - Value `IResourceProviderOperationDefinition[]` + +### ResourceProviderOperationDisplayProperties [Api20151101] + - Description `String` + - Operation `String` + - Provider `String` + - Publisher `String` + - Resource `String` + +### ResourcesIdentity [Models] + - ApplianceDefinitionId `String` + - ApplianceDefinitionName `String` + - ApplianceId `String` + - ApplianceName `String` + - ApplicationDefinitionId `String` + - ApplicationDefinitionName `String` + - ApplicationId `String` + - ApplicationId1 `String` + - ApplicationName `String` + - ApplicationObjectId `String` + - DenyAssignmentId `String` + - DeploymentName `String` + - DomainName `String` + - FeatureName `String` + - GroupId `String` + - GroupObjectId `String` + - Id `String` + - LinkId `String` + - LockName `String` + - ManagementGroupId `String` + - MemberObjectId `String` + - ObjectId `String` + - OperationId `String` + - OwnerObjectId `String` + - ParentResourcePath `String` + - PolicyAssignmentId `String` + - PolicyAssignmentName `String` + - PolicyDefinitionName `String` + - PolicySetDefinitionName `String` + - ResourceGroupName `String` + - ResourceId `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - RoleAssignmentId `String` + - RoleAssignmentName `String` + - RoleDefinitionId `String` + - RoleId `String` + - Scope `String` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - TagName `String` + - TagValue `String` + - TenantId `String` + - UpnOrObjectId `String` + +### ResourcesMoveInfo [Api20180501] + - Resource `String[]` + - TargetResourceGroup `String` + +### ResourceType [Api20150701, Api201801Preview] + - DisplayName `String` + - Name `String` + - Operation `IProviderOperation[]` + +### RoleAssignment [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - Id `String` + - Name `String` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + - Type `String` + +### RoleAssignmentCreateParameters [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentListResult [Api20150701, Api20180901Preview] + - NextLink `String` + - Value `IRoleAssignment[]` + +### RoleAssignmentProperties [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentPropertiesWithScope [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + +### RoleDefinition [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Id `String` + - Name `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - Type `String` + +### RoleDefinitionListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IRoleDefinition[]` + +### RoleDefinitionProperties [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + +### ServicePrincipal \ [Api16] + - AccountEnabled `Boolean?` + - AlternativeName `String[]` + - AppDisplayName `String` + - AppId `String` + - AppOwnerTenantId `String` + - AppRole `IAppRole[]` + - AppRoleAssignmentRequired `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - Homepage `String` + - KeyCredentials `IKeyCredential[]` + - LogoutUrl `String` + - Name `String[]` + - Oauth2Permission `IOAuth2Permission[]` + - ObjectId `String` + - ObjectType `String` + - PasswordCredentials `IPasswordCredential[]` + - PreferredTokenSigningKeyThumbprint `String` + - PublisherName `String` + - ReplyUrl `String[]` + - SamlMetadataUrl `String` + - Tag `String[]` + - Type `String` + +### ServicePrincipalBase [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalCreateParameters [Api16] + - AccountEnabled `Boolean?` + - AppId `String` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalListResult [Api16] + - OdataNextLink `String` + - Value `IServicePrincipal[]` + +### ServicePrincipalObjectResult [Api16] + - OdataMetadata `String` + - Value `String` + +### ServicePrincipalUpdateParameters [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### SignInName \ [Api16] + - Type `String` + - Value `String` + +### Sku [Api20160901Preview, Api20180501] + - Capacity `Int32?` + - Family `String` + - Model `String` + - Name `String` + - Size `String` + - Tier `String` + +### Subscription [Api20160601] + - AuthorizationSource `String` + - DisplayName `String` + - Id `String` + - PolicyLocationPlacementId `String` + - PolicyQuotaId `String` + - PolicySpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + - State `SubscriptionState?` **{Deleted, Disabled, Enabled, PastDue, Warned}** + - SubscriptionId `String` + +### SubscriptionPolicies [Api20160601] + - LocationPlacementId `String` + - QuotaId `String` + - SpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + +### TagCount [Api20180501] + - Type `String` + - Value `Int32?` + +### TagDetails [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagName `String` + - Value `ITagValue[]` + +### TagsListResult [Api20180501] + - NextLink `String` + - Value `ITagDetails[]` + +### TagValue [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagValue1 `String` + +### TargetResource [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### TemplateLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### TenantBackfillStatusResult [Api20180301Preview] + - Status `Status?` **{Cancelled, Completed, Failed, NotStarted, NotStartedButGroupsExist, Started}** + - TenantId `String` + +### TenantIdDescription [Api20160601] + - Id `String` + - TenantId `String` + +### TenantListResult [Api20160601] + - NextLink `String` + - Value `ITenantIdDescription[]` + +### User \ [Api16] + - AccountEnabled `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - PrincipalName `String` + - SignInName `ISignInName[]` + - Surname `String` + - Type `UserType?` **{Guest, Member}** + - UsageLocation `String` + +### UserBase \ [Api16] + - GivenName `String` + - ImmutableId `String` + - Surname `String` + - UsageLocation `String` + - UserType `UserType?` **{Guest, Member}** + +### UserCreateParameters \ [Api16] + - AccountEnabled `Boolean` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + +### UserGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### UserGetMemberGroupsResult [Api16] + - Value `String[]` + +### UserListResult [Api16] + - OdataNextLink `String` + - Value `IUser[]` + +### UserUpdateParameters \ [Api16] + - AccountEnabled `Boolean?` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/tools/Resources/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/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/target/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Astronomer.Astro.Management/tspconfig.yaml b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/tspconfig.yaml new file mode 100644 index 00000000000..e4f7fc17b20 --- /dev/null +++ b/tests-upgrade/tests-emitter/Astronomer.Astro.Management/tspconfig.yaml @@ -0,0 +1,79 @@ +parameters: + "service-dir": + default: "sdk/astro" +output-dir: "{project-root}/" +emit: + - "@azure-tools/typespec-autorest" +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" + disable: + "@azure-tools/typespec-azure-resource-manager/arm-common-types-version": "New rule" +options: + "@azure-tools/typespec-autorest": + emitter-output-dir: "{project-root}/.." + azure-resource-provider-folder: "resource-manager" + emit-common-types-schema: "never" + # `arm-resource-flattening` is only used for back-compat for specs existed on July 2024. All new service spec should NOT use this flag + arm-resource-flattening: true + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/astronomer.json" + "@azure-tools/typespec-ts": + azureSdkForJs: true + isModularLibrary: true + generateMetadata: true + hierarchyClient: false + experimentalExtensibleEnums: true + enableOperationGroup: true + package-dir: "arm-astro" + flavor: "azure" + packageDetails: + name: "@azure/arm-astro" + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-astro" + package-name: "{package-dir}" + flavor: "azure" + generate-test: true + generate-sample: true + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "Astro/Astro.Autorest" + clear-output-folder: true + azure: true + module-version: 0.1.0 + skip-model-cmdlets: false + help-link-prefix: https://learn.microsoft.com/powershell/module/ + metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + description: 'Microsoft Azure PowerShell: Astro cmdlets' + copyright: Microsoft Corporation. All rights reserved. + tags: Azure ResourceManager ARM PSModule Sphere + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell + prefix: 'Az' + subject-prefix: 'Astro' + service-name: Astro + module-name: "{prefix}.{service-name}" + namespace: "Microsoft.Azure.PowerShell.Cmdlets.{service-name}" + use-namespace-folders: false + # output-folder: "{output-dir}" + exclude-tableview-properties: + - Id + - Type + directive: + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - where: + variant: ^(Create|Update)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + verb: Set + hide: true diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/.gitattributes b/tests-upgrade/tests-emitter/AzureAI.Assets/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.csproj b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.csproj new file mode 100644 index 00000000000..20134d31f48 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.MachineLearningServices.private + false + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices + true + false + ./bin + $(OutputPath) + Az.MachineLearningServices.nuspec + true + + + 1998, 1591 + true + + + + false + TRACE;DEBUG;NETSTANDARD + + + + true + true + MSSharedLibKey.snk + TRACE;RELEASE;NETSTANDARD;SIGN + + + + + + + + + $(DefaultItemExcludes);resources/** + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.nuspec b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.nuspec new file mode 100644 index 00000000000..115707cdc18 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.nuspec @@ -0,0 +1,32 @@ + + + + Az.MachineLearningServices + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: MachineLearningServices cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule MachineLearningServices + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.psm1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.psm1 new file mode 100644 index 00000000000..2fdc6da5d2b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/Az.MachineLearningServices.psm1 @@ -0,0 +1,126 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.MachineLearningServices.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # Tweaks the pipeline per call + $instance.AddRequestUserAgentHandler = $VTable.AddRequestUserAgentHandler + + # Tweaks the pipeline per call + $instance.AddPatchRequestUriHandler = $VTable.AddPatchRequestUriHandler + + # Tweaks the pipeline per call + $instance.AddAuthorizeRequestHandler = $VTable.AddAuthorizeRequestHandler + + + # 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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/AzureAI.Assets/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/AzureAI.Assets/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/README.md new file mode 100644 index 00000000000..ebb517966ce --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/README.md @@ -0,0 +1,24 @@ + +# Az.MachineLearningServices +This directory contains the PowerShell module for the MachineLearningServices service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.MachineLearningServices`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/build-module.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/build-module.ps1 new file mode 100644 index 00000000000..92e9d83269e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $NotIsolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +$isAzure = [System.Convert]::ToBoolean('true') + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.MachineLearningServices' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: MachineLearningServices cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.MachineLearningServices.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and ((-not (Test-Path -Path $resourceModule)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..ecd022b6843 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if (''.length -gt 0) { + $ModuleName = '' + } else { + $ModuleName = 'Az.MachineLearningServices' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('MLWorkspace')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'MLWorkspace' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/Az.MachineLearningServices.custom.psm1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/Az.MachineLearningServices.custom.psm1 new file mode 100644 index 00000000000..ba67e1d8f77 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/Az.MachineLearningServices.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.MachineLearningServices.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/README.md new file mode 100644 index 00000000000..d37e5a5cd56 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.MachineLearningServices` 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.MachineLearningServices.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.MachineLearningServices` 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.MachineLearningServices.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.MachineLearningServices.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.MachineLearningServices`. 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.MachineLearningServices.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.MachineLearningServices`. +- `Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.MachineLearningServices`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/docs/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/docs/README.md new file mode 100644 index 00000000000..b8b01ab0c03 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.MachineLearningServices` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.MachineLearningServices` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/examples/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/export-surface.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/export-surface.ps1 new file mode 100644 index 00000000000..9c86d33dc8a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.MachineLearningServices.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.MachineLearningServices' +$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/tests-upgrade/tests-emitter/AzureAI.Assets/target/exports/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/exports/README.md new file mode 100644 index 00000000000..ff9db697a6a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.MachineLearningServices`. No other cmdlets in this repository are directly exported. What that means is the `Az.MachineLearningServices` module will run [Export-ModuleMember](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.MachineLearningServices.private.dll`) and from the `..\custom\Az.MachineLearningServices.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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-help.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-help.ps1 new file mode 100644 index 00000000000..ba6af29053e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MachineLearningServices.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.MachineLearningServices.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..aeca828bb50 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generate-portal-ux.ps1 @@ -0,0 +1,383 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.MachineLearningServices' +$rootModuleName = '' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + if ($Null -eq $example) + { + $example = @() + } + + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + if ($Null -eq $signature) + { + $signature = @() + } + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/Module.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/Module.cs new file mode 100644 index 00000000000..8664b5119b4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/Module.cs @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + using TokenAudienceConverterDelegate = global::System.Func; + using AuthorizeRequestDelegate = 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>>, global::System.Func, global::System.Collections.Generic.IDictionary>; + using System.Collections.Generic; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + private string _endpointResourceIdKeyName = @"AzureMachineLearningServicesEndpointResourceId"; + + private string _endpointSuffixKeyName = @""; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + private TokenAudienceConverterDelegate _tokenAudienceConverter = null; + + public bool _useProxy = false; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// The delegate to call before each new request to add authorization. + public AuthorizeRequestDelegate AddAuthorizeRequestHandler { get; set; } + + /// The delegate to call before each new request to patch request uri. + public NewRequestPipelineDelegate AddPatchRequestUriHandler { get; set; } + + /// The delegate to call before each new request to add request user agent. + public NewRequestPipelineDelegate AddRequestUserAgentHandler { get; set; } + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.MachineLearningServices"; + + /// The delegate to call when this module is loaded (supporting a commmon module). + public ModuleLoadPipelineDelegate OnModuleLoad { 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.MachineLearningServices"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_useProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + AddRequestUserAgentHandler?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + AddPatchRequestUriHandler?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + AddAuthorizeRequestHandler?.Invoke( invocationInfo, _endpointResourceIdKeyName,_endpointSuffixKeyName, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); }, _tokenAudienceConverter, extensibleParameters ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/MachineLearningServices.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/MachineLearningServices.cs new file mode 100644 index 00000000000..7a941996a23 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/MachineLearningServices.cs @@ -0,0 +1,4460 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// + /// Low-level API implementation for the Azure Machine Learning Data Plane Services service. + /// + public partial class MachineLearningServices + { + + /// update a IndexVersion. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of an Index Version. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IndexesCreateOrUpdate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a IndexVersion. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of an Index Version. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IndexesCreateOrUpdateViaIdentity(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a IndexVersion. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of an Index Version. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IndexesCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a IndexVersion. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Json string supplied to the IndexesCreateOrUpdate operation + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.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 IndexesCreateOrUpdateViaJsonString(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a IndexVersion. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Json string supplied to the IndexesCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesCreateOrUpdateViaJsonStringWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a IndexVersion. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of an Index Version. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task IndexesCreateOrUpdateWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.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 IndexesCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of an Index Version. + /// 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 IndexesCreateOrUpdate_Validate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(version),version); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Get a specific version of an Index. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesGet(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// Name of the index. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesGetLatest(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGetLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesGetLatestViaIdentity(global::System.String viaIdentity, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGetLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetLatestViaIdentityWithResult(global::System.String viaIdentity, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetLatestWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// Name of the index. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetLatestWithResult(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetLatestWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetLatestWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetLatest_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the index. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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 IndexesGetLatest_Validate(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + } + } + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// Name of the index. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 IndexesGetNextVersion(string name, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGetNextVersion_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 IndexesGetNextVersionViaIdentity(global::System.String viaIdentity, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGetNextVersion_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetNextVersionViaIdentityWithResult(global::System.String viaIdentity, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetNextVersionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// Name of the index. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetNextVersionWithResult(string name, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetNextVersionWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetNextVersionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.VersionInfo.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetNextVersion_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.VersionInfo.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Name of the index. + /// 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 IndexesGetNextVersion_Validate(string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, string name, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + } + } + + /// Get a specific version of an Index. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesGetViaIdentity(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a specific version of an Index. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetViaIdentityWithResult(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a specific version of an Index. + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesGet_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the index. + /// Version of the index. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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 IndexesGet_Validate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(version),version); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// List the versions of an Index given the name. + /// Name of the index. + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesList(string name, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each index. Latest is defined by most recent created by date. + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 IndexesListLatest(int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesListLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each index. Latest is defined by most recent created by date. + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 IndexesListLatestViaIdentity(global::System.String viaIdentity, int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesListLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each index. Latest is defined by most recent created by date. + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListLatestViaIdentityWithResult(global::System.String viaIdentity, int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesListLatestWithResult_Call (request, eventListener,sender); + } + } + + /// + /// List the latest version of each index. Latest is defined by most recent created by date. + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListLatestWithResult(int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesListLatestWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListLatestWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedIndex.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListLatest_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedIndex.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 IndexesListLatest_Validate(string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, int? top, int? skip, int? maxpagesize, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + } + } + + /// List the versions of an Index given the name. + /// + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 IndexesListViaIdentity(global::System.String viaIdentity, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.IndexesList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the versions of an Index given the name. + /// + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListViaIdentityWithResult(global::System.String viaIdentity, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/indexes/(?[^/]+)/versions$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/indexes/{name}/versions'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + name + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesListWithResult_Call (request, eventListener,sender); + } + } + + /// List the versions of an Index given the name. + /// Name of the index. + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListWithResult(string name, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/indexes/" + + global::System.Uri.EscapeDataString(name) + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.IndexesListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedIndex.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 IndexesList_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedIndex.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the index. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 IndexesList_Validate(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(listViewType),listViewType); + await eventListener.AssertNotNull(nameof(orderby),orderby); + await eventListener.AssertNotNull(nameof(tags),tags); + } + } + + /// update a Prompt + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of a Prompt Version. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PromptsCreateOrUpdate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a Prompt + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of a Prompt Version. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PromptsCreateOrUpdateViaIdentity(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt body, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a Prompt + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of a Prompt Version. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PromptsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Prompt + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Json string supplied to the PromptsCreateOrUpdate operation + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.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 PromptsCreateOrUpdateViaJsonString(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsCreateOrUpdate_Call (request, onCreated,onOk,onDefault,eventListener,sender); + } + } + + /// update a Prompt + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Json string supplied to the PromptsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsCreateOrUpdateViaJsonStringWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a Prompt + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of a Prompt Version. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task PromptsCreateOrUpdateWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 201 (Created). + /// 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.MachineLearningServices.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 PromptsCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func, global::System.Threading.Tasks.Task> onCreated, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + case global::System.Net.HttpStatusCode.Created: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// Properties of a Prompt Version. + /// 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 PromptsCreateOrUpdate_Validate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt body, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(version),version); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Get a specific version of a Prompt. + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsGet(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// Name of the prompt + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsGetLatest(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGetLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsGetLatestViaIdentity(global::System.String viaIdentity, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGetLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetLatestViaIdentityWithResult(global::System.String viaIdentity, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetLatestWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// Name of the prompt + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetLatestWithResult(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetLatestWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetLatestWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetLatest_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the prompt + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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 PromptsGetLatest_Validate(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + } + } + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// Name of the prompt + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 PromptsGetNextVersion(string name, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGetNextVersion_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 PromptsGetNextVersionViaIdentity(global::System.String viaIdentity, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGetNextVersion_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetNextVersionViaIdentityWithResult(global::System.String viaIdentity, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetNextVersionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// Name of the prompt + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetNextVersionWithResult(string name, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + ":getNextVersion" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetNextVersionWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetNextVersionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.VersionInfo.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetNextVersion_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.VersionInfo.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Name of the prompt + /// 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 PromptsGetNextVersion_Validate(string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, string name, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + } + } + + /// Get a specific version of a Prompt. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsGetViaIdentity(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a specific version of a Prompt. + /// + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetViaIdentityWithResult(global::System.String viaIdentity, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions/(?[^/]+)$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions/{version}'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + var version = _match.Groups["version"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions/" + + version + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a specific version of a Prompt. + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetWithResult(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions/" + + global::System.Uri.EscapeDataString(version) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsGet_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the prompt + /// Version of the prompt + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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 PromptsGet_Validate(string name, string version, string resourceGroupName, string workspaceName, string endpoint, string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(version),version); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// List the versions of a Prompt given the name. + /// Name of the prompt + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsList(string name, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each prompt. Latest is defined by most recent created by date. + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 PromptsListLatest(int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsListLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each prompt. Latest is defined by most recent created by date. + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// 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.MachineLearningServices.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 PromptsListLatestViaIdentity(global::System.String viaIdentity, int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsListLatest_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// List the latest version of each prompt. Latest is defined by most recent created by date. + /// + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListLatestViaIdentityWithResult(global::System.String viaIdentity, int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsListLatestWithResult_Call (request, eventListener,sender); + } + } + + /// + /// List the latest version of each prompt. Latest is defined by most recent created by date. + /// + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListLatestWithResult(int? top, int? skip, int? maxpagesize, string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsListLatestWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListLatestWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedPrompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListLatest_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedPrompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Supported Azure-AI asset endpoints. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 PromptsListLatest_Validate(string endpoint, string subscriptionId, string resourceGroupName, string workspaceName, int? top, int? skip, int? maxpagesize, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + } + } + + /// List the versions of a Prompt given the name. + /// + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// 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.MachineLearningServices.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 PromptsListViaIdentity(global::System.String viaIdentity, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.PromptsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the versions of a Prompt given the name. + /// + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListViaIdentityWithResult(global::System.String viaIdentity, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/prompts/(?[^/]+)/versions$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/prompts/{name}/versions'"); + } + + // replace URI parameters with values from identity + var name = _match.Groups["name"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + name + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsListWithResult_Call (request, eventListener,sender); + } + } + + /// List the versions of a Prompt given the name. + /// Name of the prompt + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListWithResult(string name, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-05-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/prompts/" + + global::System.Uri.EscapeDataString(name) + + "/versions" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + + "&" + + "listViewType=" + global::System.Uri.EscapeDataString(listViewType) + + "&" + + (string.IsNullOrEmpty(orderby) ? global::System.String.Empty : "orderby=" + global::System.Uri.EscapeDataString(orderby)) + + "&" + + (string.IsNullOrEmpty(tags) ? global::System.String.Empty : "tags=" + global::System.Uri.EscapeDataString(tags)) + + "&" + + (null == top ? global::System.String.Empty : "top=" + global::System.Uri.EscapeDataString(top.ToString())) + + "&" + + (null == skip ? global::System.String.Empty : "skip=" + global::System.Uri.EscapeDataString(skip.ToString())) + + "&" + + (null == maxpagesize ? global::System.String.Empty : "maxpagesize=" + global::System.Uri.EscapeDataString(maxpagesize.ToString())) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"{endpoint}/genericasset/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{workspaceName}{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.PromptsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedPrompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 PromptsList_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.MachineLearningServices.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PagedPrompt.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.AzureCoreFoundationsErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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. + /// + /// Name of the prompt + /// The ID of the target subscription. + /// The name of the Resource Group. + /// The name of the AzureML workspace or AI project. + /// Supported Azure-AI asset endpoints. + /// View type for including/excluding (for example) archived entities. + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// The number of result items to return. + /// The number of result items to skip. + /// The maximum number of result items per page. + /// 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 PromptsList_Validate(string name, string subscriptionId, string resourceGroupName, string workspaceName, string endpoint, string listViewType, string orderby, string tags, int? top, int? skip, int? maxpagesize, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(name),name); + await eventListener.AssertMaximumLength(nameof(name),name,254); + await eventListener.AssertRegEx(nameof(name), name, @"^[a-zA-Z0-9][a-zA-Z0-9-_]*$"); + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); + await eventListener.AssertNotNull(nameof(workspaceName),workspaceName); + await eventListener.AssertNotNull(nameof(endpoint),endpoint); + await eventListener.AssertRegEx(nameof(endpoint),endpoint,@"^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$"); + await eventListener.AssertNotNull(nameof(listViewType),listViewType); + await eventListener.AssertNotNull(nameof(orderby),orderby); + await eventListener.AssertNotNull(nameof(tags),tags); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..e10a1c60daf --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.PowerShell.cs @@ -0,0 +1,197 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// A response containing error details. + [System.ComponentModel.TypeConverter(typeof(AzureCoreFoundationsErrorResponseTypeConverter))] + public partial class AzureCoreFoundationsErrorResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AzureCoreFoundationsErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal AzureCoreFoundationsErrorResponse(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.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.MachineLearningServices.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AzureCoreFoundationsErrorResponse(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.MachineLearningServices.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AzureCoreFoundationsErrorResponse(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.MachineLearningServices.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..e0107f63ae5 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.TypeConverter.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AzureCoreFoundationsErrorResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AzureCoreFoundationsErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AzureCoreFoundationsErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AzureCoreFoundationsErrorResponse.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.cs new file mode 100644 index 00000000000..30aef105311 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// A response containing error details. + public partial class AzureCoreFoundationsErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal + { + + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Code = value ; } + + /// An array of details about specific errors that led to this reported error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Detail = value ?? null /* arrayOf */; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Error()); set => this._error = value; } + + /// + /// An object containing more specific information than the current object about the error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Innererror; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Innererror = value ?? null /* model class */; } + + /// A human-readable representation of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Message = value ; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Error()); set { {_error = value;} } } + + /// The target of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)Error).Target = value ?? null; } + + /// Creates an new instance. + public AzureCoreFoundationsErrorResponse() + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.json.cs new file mode 100644 index 00000000000..4e0b37f7ace --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/AzureCoreFoundationsErrorResponse.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// A response containing error details. + public partial class AzureCoreFoundationsErrorResponse + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal AzureCoreFoundationsErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Models.Error.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new AzureCoreFoundationsErrorResponse(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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.PowerShell.cs new file mode 100644 index 00000000000..ba5a4f25cdd --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// The error object. + [System.ComponentModel.TypeConverter(typeof(ErrorTypeConverter))] + public partial class Error + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Error(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Error(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Error(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom)); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Error(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ErrorTypeConverter.ConvertFrom)); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.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.MachineLearningServices.Models.IError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error object. + [System.ComponentModel.TypeConverter(typeof(ErrorTypeConverter))] + public partial interface IError + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.TypeConverter.cs new file mode 100644 index 00000000000..6497cf722a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Error.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Error.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Error.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.cs new file mode 100644 index 00000000000..80242914122 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// The error object. + public partial class Error : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorInternal + { + + /// Backing field for property. + private string _code; + + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// An array of details about specific errors that led to this reported error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; set => this._detail = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError _innererror; + + /// + /// An object containing more specific information than the current object about the error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get => (this._innererror = this._innererror ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerError()); set => this._innererror = value; } + + /// Backing field for property. + private string _message; + + /// A human-readable representation of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Message { get => this._message; set => this._message = value; } + + /// Backing field for property. + private string _target; + + /// The target of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Target { get => this._target; set => this._target = value; } + + /// Creates an new instance. + public Error() + { + + } + } + /// The error object. + public partial interface IError : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"One of a server-defined set of error codes.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// An array of details about specific errors that led to this reported error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"An array of details about specific errors that led to this reported error.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError) })] + System.Collections.Generic.List Detail { get; set; } + /// + /// An object containing more specific information than the current object about the error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"An object containing more specific information than the current object about the error.", + SerializedName = @"innererror", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + /// A human-readable representation of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A human-readable representation of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// The target of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The target of the error.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; set; } + + } + /// The error object. + internal partial interface IErrorInternal + + { + /// One of a server-defined set of error codes. + string Code { get; set; } + /// An array of details about specific errors that led to this reported error. + System.Collections.Generic.List Detail { get; set; } + /// + /// An object containing more specific information than the current object about the error. + /// + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + /// A human-readable representation of the error. + string Message { get; set; } + /// The target of the error. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.json.cs new file mode 100644 index 00000000000..37e8c0b769a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Error.json.cs @@ -0,0 +1,122 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// The error object. + public partial class Error + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal Error(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError) (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Error.FromJson(__u) )) ))() : null : _detail;} + {_innererror = If( json?.PropertyT("innererror"), out var __jsonInnererror) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerError.FromJson(__jsonInnererror) : _innererror;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new Error(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + AddIf( null != this._innererror ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._innererror.ToJson(null,serializationMode) : null, "innererror" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..79da492b1c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// A response containing error details. + [System.ComponentModel.TypeConverter(typeof(AzureCoreFoundationsErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.cs new file mode 100644 index 00000000000..a8b979c9ffb --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponse.cs @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// A response containing error details. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"One of a server-defined set of error codes.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// An array of details about specific errors that led to this reported error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"An array of details about specific errors that led to this reported error.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError) })] + System.Collections.Generic.List Detail { get; set; } + /// + /// An object containing more specific information than the current object about the error. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"An object containing more specific information than the current object about the error.", + SerializedName = @"innererror", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + /// A human-readable representation of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"A human-readable representation of the error.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; set; } + /// The target of the error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The target of the error.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponseInternal.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponseInternal.cs new file mode 100644 index 00000000000..f7d5ead3a18 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/IErrorResponseInternal.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// A response containing error details. + internal partial interface IErrorResponseInternal + + { + /// One of a server-defined set of error codes. + string Code { get; set; } + /// An array of details about specific errors that led to this reported error. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IError Error { get; set; } + /// + /// An object containing more specific information than the current object about the error. + /// + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + /// A human-readable representation of the error. + string Message { get; set; } + /// The target of the error. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.PowerShell.cs new file mode 100644 index 00000000000..d2a3bbbfeb9 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.PowerShell.cs @@ -0,0 +1,242 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Index resource Definition + [System.ComponentModel.TypeConverter(typeof(IndexTypeConverter))] + public partial class Index + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Index(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.MachineLearningServices.Models.IIndex DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Index(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.MachineLearningServices.Models.IIndex FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Index(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("StorageUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).StorageUri = (string) content.GetValueForProperty("StorageUri",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).StorageUri, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Index(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("StorageUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).StorageUri = (string) content.GetValueForProperty("StorageUri",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).StorageUri, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Index resource Definition + [System.ComponentModel.TypeConverter(typeof(IndexTypeConverter))] + public partial interface IIndex + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.TypeConverter.cs new file mode 100644 index 00000000000..910cd3b4602 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class IndexTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Index.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Index.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Index.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.cs new file mode 100644 index 00000000000..5d2cb6ed0e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.cs @@ -0,0 +1,275 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Index resource Definition + public partial class Index : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal + { + + /// Backing field for property. + private string _description; + + /// Description information of the asset. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _id; + + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt = value; } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy = value; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType = value; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndexInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags _property; + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags()); set => this._property = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private string _stage; + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Stage { get => this._stage; set => this._stage = value; } + + /// Backing field for property. + private string _storageUri; + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string StorageUri { get => this._storageUri; set => this._storageUri = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData _systemData; + + /// Metadata containing createdBy and modifiedBy information. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData()); } + + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags _tag; + + /// Asset's tags. Unlike properties, tags are fully mutable. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags()); set => this._tag = value; } + + /// Creates an new instance. + public Index() + { + + } + } + /// Index resource Definition + public partial interface IIndex : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// Description information of the asset. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get; set; } + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string Stage { get; set; } + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + string StorageUri { get; set; } + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp the resource was created at.", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity type that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// Asset's tags. Unlike properties, tags are fully mutable. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get; set; } + + } + /// Index resource Definition + internal partial interface IIndexInternal + + { + /// Description information of the asset. + string Description { get; set; } + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + string Id { get; set; } + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get; set; } + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + string Stage { get; set; } + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + string StorageUri { get; set; } + /// Metadata containing createdBy and modifiedBy information. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData SystemData { get; set; } + /// The timestamp the resource was created at. + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The identity type that created the resource. + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// Asset's tags. Unlike properties, tags are fully mutable. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.json.cs new file mode 100644 index 00000000000..27e2b203589 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Index.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Index resource Definition + public partial class Index + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new Index(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal Index(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_stage = If( json?.PropertyT("stage"), out var __jsonStage) ? (string)__jsonStage : (string)_stage;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags.FromJson(__jsonTags) : _tag;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags.FromJson(__jsonProperties) : _property;} + {_storageUri = If( json?.PropertyT("storageUri"), out var __jsonStorageUri) ? (string)__jsonStorageUri : (string)_storageUri;} + 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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._stage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._stage.ToString()) : null, "stage" ,container.Add ); + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != (((object)this._storageUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._storageUri.ToString()) : null, "storageUri" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.PowerShell.cs new file mode 100644 index 00000000000..a20d1c66e72 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.PowerShell.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + /// + [System.ComponentModel.TypeConverter(typeof(InnerErrorTypeConverter))] + public partial class InnerError + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new InnerError(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.MachineLearningServices.Models.IInnerError DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new InnerError(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.MachineLearningServices.Models.IInnerError FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal InnerError(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal InnerError(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Innererror")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Innererror = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) content.GetValueForProperty("Innererror",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal)this).Innererror, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerErrorTypeConverter.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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + [System.ComponentModel.TypeConverter(typeof(InnerErrorTypeConverter))] + public partial interface IInnerError + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.TypeConverter.cs new file mode 100644 index 00000000000..059b48ac64d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class InnerErrorTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return InnerError.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return InnerError.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return InnerError.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.cs new file mode 100644 index 00000000000..a1365f8ef1b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + /// + public partial class InnerError : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerErrorInternal + { + + /// Backing field for property. + private string _code; + + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Code { get => this._code; set => this._code = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError _innererror; + + /// Inner error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get => (this._innererror = this._innererror ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerError()); set => this._innererror = value; } + + /// Creates an new instance. + public InnerError() + { + + } + } + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + public partial interface IInnerError : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// One of a server-defined set of error codes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"One of a server-defined set of error codes.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; set; } + /// Inner error. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Inner error.", + SerializedName = @"innererror", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + + } + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + internal partial interface IInnerErrorInternal + + { + /// One of a server-defined set of error codes. + string Code { get; set; } + /// Inner error. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError Innererror { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.json.cs new file mode 100644 index 00000000000..52dab86e8aa --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/InnerError.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// + /// An object containing more specific information about the error. As per Microsoft One API guidelines - https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + /// + public partial class InnerError + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IInnerError FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new InnerError(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal InnerError(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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;} + {_innererror = If( json?.PropertyT("innererror"), out var __jsonInnererror) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.InnerError.FromJson(__jsonInnererror) : _innererror;} + 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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + AddIf( null != this._innererror ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._innererror.ToJson(null,serializationMode) : null, "innererror" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.PowerShell.cs new file mode 100644 index 00000000000..e7bd426c30c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.PowerShell.cs @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(MachineLearningServicesIdentityTypeConverter))] + public partial class MachineLearningServicesIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MachineLearningServicesIdentity(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.MachineLearningServices.Models.IMachineLearningServicesIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MachineLearningServicesIdentity(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.MachineLearningServices.Models.IMachineLearningServicesIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MachineLearningServicesIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Version")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Version = (string) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Version, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)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 MachineLearningServicesIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Version")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Version = (string) content.GetValueForProperty("Version",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Version, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal)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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(MachineLearningServicesIdentityTypeConverter))] + public partial interface IMachineLearningServicesIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.TypeConverter.cs new file mode 100644 index 00000000000..4a5395baa36 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.TypeConverter.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MachineLearningServicesIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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 MachineLearningServicesIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MachineLearningServicesIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MachineLearningServicesIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MachineLearningServicesIdentity.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.cs new file mode 100644 index 00000000000..b828fd844c3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + public partial class MachineLearningServicesIdentity : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentityInternal + { + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _name; + + /// Name of the index. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Version { get => this._version; set => this._version = value; } + + /// Creates an new instance. + public MachineLearningServicesIdentity() + { + + } + } + public partial interface IMachineLearningServicesIdentity : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Name of the index. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + /// Version of the index. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + string Version { get; set; } + + } + internal partial interface IMachineLearningServicesIdentityInternal + + { + /// Resource identity path + string Id { get; set; } + /// Name of the index. + string Name { get; set; } + /// Version of the index. + string Version { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.json.cs new file mode 100644 index 00000000000..840f141bfec --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/MachineLearningServicesIdentity.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + public partial class MachineLearningServicesIdentity + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new MachineLearningServicesIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal MachineLearningServicesIdentity(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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;} + {_version = If( json?.PropertyT("version"), out var __jsonVersion) ? (string)__jsonVersion : (string)_version;} + {_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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AddIf( null != (((object)this._version)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._version.ToString()) : null, "version" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.PowerShell.cs new file mode 100644 index 00000000000..38c92265a14 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Paged collection of IndexVersion items. + [System.ComponentModel.TypeConverter(typeof(PagedIndexTypeConverter))] + public partial class PagedIndex + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PagedIndex(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.MachineLearningServices.Models.IPagedIndex DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PagedIndex(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.MachineLearningServices.Models.IPagedIndex FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PagedIndex(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IndexTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal PagedIndex(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IndexTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Paged collection of IndexVersion items. + [System.ComponentModel.TypeConverter(typeof(PagedIndexTypeConverter))] + public partial interface IPagedIndex + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.TypeConverter.cs new file mode 100644 index 00000000000..2dde18022fe --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PagedIndexTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PagedIndex.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PagedIndex.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PagedIndex.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.cs new file mode 100644 index 00000000000..cc71df3da68 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Paged collection of IndexVersion items. + public partial class PagedIndex : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndexInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The list of Indexes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PagedIndex() + { + + } + } + /// Paged collection of IndexVersion items. + public partial interface IPagedIndex : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of Indexes. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of Indexes.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Paged collection of IndexVersion items. + internal partial interface IPagedIndexInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The list of Indexes. + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.json.cs new file mode 100644 index 00000000000..0571cc90bdf --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedIndex.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Paged collection of IndexVersion items. + public partial class PagedIndex + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new PagedIndex(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal PagedIndex(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex) (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.PowerShell.cs new file mode 100644 index 00000000000..577f00b8677 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Paged collection of PromptVersion items + [System.ComponentModel.TypeConverter(typeof(PagedPromptTypeConverter))] + public partial class PagedPrompt + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PagedPrompt(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.MachineLearningServices.Models.IPagedPrompt DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PagedPrompt(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.MachineLearningServices.Models.IPagedPrompt FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PagedPrompt(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PromptTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal PagedPrompt(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.PromptTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Paged collection of PromptVersion items + [System.ComponentModel.TypeConverter(typeof(PagedPromptTypeConverter))] + public partial interface IPagedPrompt + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.TypeConverter.cs new file mode 100644 index 00000000000..8107e38327c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PagedPromptTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PagedPrompt.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PagedPrompt.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PagedPrompt.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.cs new file mode 100644 index 00000000000..9e98ac39079 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Paged collection of PromptVersion items + public partial class PagedPrompt : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPromptInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The list of Prompts. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public PagedPrompt() + { + + } + } + /// Paged collection of PromptVersion items + public partial interface IPagedPrompt : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The list of Prompts. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The list of Prompts.", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt) })] + System.Collections.Generic.List Value { get; set; } + + } + /// Paged collection of PromptVersion items + internal partial interface IPagedPromptInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The list of Prompts. + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.json.cs new file mode 100644 index 00000000000..8f4484be750 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/PagedPrompt.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Paged collection of PromptVersion items + public partial class PagedPrompt + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new PagedPrompt(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal PagedPrompt(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt) (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.PowerShell.cs new file mode 100644 index 00000000000..e335f5ec182 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Prompt resource definition + [System.ComponentModel.TypeConverter(typeof(PromptTypeConverter))] + public partial class Prompt + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Prompt(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.MachineLearningServices.Models.IPrompt DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Prompt(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.MachineLearningServices.Models.IPrompt FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Prompt(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("DataUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).DataUri = (string) content.GetValueForProperty("DataUri",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).DataUri, global::System.Convert.ToString); + } + if (content.Contains("TemplatePath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).TemplatePath = (string) content.GetValueForProperty("TemplatePath",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).TemplatePath, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Prompt(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Stage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Stage = (string) content.GetValueForProperty("Stage",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Stage, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Description, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("DataUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).DataUri = (string) content.GetValueForProperty("DataUri",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).DataUri, global::System.Convert.ToString); + } + if (content.Contains("TemplatePath")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).TemplatePath = (string) content.GetValueForProperty("TemplatePath",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).TemplatePath, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Prompt resource definition + [System.ComponentModel.TypeConverter(typeof(PromptTypeConverter))] + public partial interface IPrompt + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.TypeConverter.cs new file mode 100644 index 00000000000..424e7395166 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PromptTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Prompt.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Prompt.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Prompt.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.cs new file mode 100644 index 00000000000..be9adc7448d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.cs @@ -0,0 +1,295 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Prompt resource definition + public partial class Prompt : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal + { + + /// Backing field for property. + private string _dataUri; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string DataUri { get => this._dataUri; set => this._dataUri = value; } + + /// Backing field for property. + private string _description; + + /// Description information of the asset. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Description { get => this._description; set => this._description = value; } + + /// Backing field for property. + private string _id; + + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for SystemDataCreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt = value; } + + /// Internal Acessors for SystemDataCreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy = value; } + + /// Internal Acessors for SystemDataCreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType = value; } + + /// Internal Acessors for SystemDataLastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPromptInternal.SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags _property; + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags()); set => this._property = value; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private string _stage; + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string Stage { get => this._stage; set => this._stage = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData _systemData; + + /// Metadata containing createdBy and modifiedBy information. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData()); } + + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedAt; } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedBy; } + + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).CreatedByType; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)SystemData).LastModifiedAt; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags _tag; + + /// Asset's tags. Unlike properties, tags are fully mutable. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags()); set => this._tag = value; } + + /// Backing field for property. + private string _templatePath; + + /// Relative path of the prompt data file at the dataUri location + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string TemplatePath { get => this._templatePath; set => this._templatePath = value; } + + /// Creates an new instance. + public Prompt() + { + + } + } + /// Prompt resource definition + public partial interface IPrompt : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + string DataUri { get; set; } + /// Description information of the asset. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; set; } + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index.", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; } + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get; set; } + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + string Stage { get; set; } + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp the resource was created at.", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity type that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// Asset's tags. Unlike properties, tags are fully mutable. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get; set; } + /// Relative path of the prompt data file at the dataUri location + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + string TemplatePath { get; set; } + + } + /// Prompt resource definition + internal partial interface IPromptInternal + + { + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + string DataUri { get; set; } + /// Description information of the asset. + string Description { get; set; } + /// + /// Fully qualified resource Id: azureml://workspace/{workspaceName}/indexes/{name}/versions/{version} of the index. + /// + string Id { get; set; } + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get; set; } + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + string Stage { get; set; } + /// Metadata containing createdBy and modifiedBy information. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData SystemData { get; set; } + /// The timestamp the resource was created at. + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The identity type that created the resource. + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// Asset's tags. Unlike properties, tags are fully mutable. + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get; set; } + /// Relative path of the prompt data file at the dataUri location + string TemplatePath { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.json.cs new file mode 100644 index 00000000000..f2413950421 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Prompt.json.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Prompt resource definition + public partial class Prompt + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new Prompt(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal Prompt(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_stage = If( json?.PropertyT("stage"), out var __jsonStage) ? (string)__jsonStage : (string)_stage;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags.FromJson(__jsonTags) : _tag;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Tags.FromJson(__jsonProperties) : _property;} + {_dataUri = If( json?.PropertyT("dataUri"), out var __jsonDataUri) ? (string)__jsonDataUri : (string)_dataUri;} + {_templatePath = If( json?.PropertyT("templatePath"), out var __jsonTemplatePath) ? (string)__jsonTemplatePath : (string)_templatePath;} + 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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + AddIf( null != (((object)this._stage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._stage.ToString()) : null, "stage" ,container.Add ); + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != (((object)this._dataUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._dataUri.ToString()) : null, "dataUri" ,container.Add ); + AddIf( null != (((object)this._templatePath)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._templatePath.ToString()) : null, "templatePath" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..b9310c7e55a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..3c567c0b059 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..c145f730c46 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; } + + /// Backing field for property. + private string _createdByType; + + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; } + + /// Internal Acessors for CreatedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal.CreatedAt { get => this._createdAt; set { {_createdAt = value;} } } + + /// Internal Acessors for CreatedBy + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal.CreatedBy { get => this._createdBy; set { {_createdBy = value;} } } + + /// Internal Acessors for CreatedByType + string Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal.CreatedByType { get => this._createdByType; set { {_createdByType = value;} } } + + /// Internal Acessors for LastModifiedAt + global::System.DateTime? Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemDataInternal.LastModifiedAt { get => this._lastModifiedAt; set { {_lastModifiedAt = value;} } } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// The timestamp the resource was created at. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp the resource was created at.", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; } + /// The identity type that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity type that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + string CreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp the resource was created at. + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The identity type that created the resource. + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..df61f9dee84 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/SystemData.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.PowerShell.cs new file mode 100644 index 00000000000..2ee7da9f865 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Asset's tags. Unlike properties, tags are fully mutable. + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.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.MachineLearningServices.Models.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.MachineLearningServices.Models.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 + // 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 Tags(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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Asset's tags. Unlike properties, tags are fully mutable. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.TypeConverter.cs new file mode 100644 index 00000000000..d4ce71d7f50 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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 type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.cs new file mode 100644 index 00000000000..ef44d2baf29 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Asset's tags. Unlike properties, tags are fully mutable. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITagsInternal + { + + /// Creates an new instance. + public Tags() + { + + } + } + /// Asset's tags. Unlike properties, tags are fully mutable. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray + { + + } + /// Asset's tags. Unlike properties, tags are fully mutable. + internal partial interface ITagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.dictionary.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.dictionary.cs new file mode 100644 index 00000000000..9ec97acec7c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Models.Tags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.json.cs new file mode 100644 index 00000000000..a4241e68b38 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/Tags.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Asset's tags. Unlike properties, tags are fully mutable. + 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.PowerShell.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.PowerShell.cs new file mode 100644 index 00000000000..3cc66c529af --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// Next version definition. + [System.ComponentModel.TypeConverter(typeof(VersionInfoTypeConverter))] + public partial class VersionInfo + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new VersionInfo(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.MachineLearningServices.Models.IVersionInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new VersionInfo(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.MachineLearningServices.Models.IVersionInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal VersionInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NextVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).NextVersion = (long?) content.GetValueForProperty("NextVersion",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).NextVersion, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("LatestVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).LatestVersion = (string) content.GetValueForProperty("LatestVersion",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).LatestVersion, 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 VersionInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NextVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).NextVersion = (long?) content.GetValueForProperty("NextVersion",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).NextVersion, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("LatestVersion")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).LatestVersion = (string) content.GetValueForProperty("LatestVersion",((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal)this).LatestVersion, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// Next version definition. + [System.ComponentModel.TypeConverter(typeof(VersionInfoTypeConverter))] + public partial interface IVersionInfo + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.TypeConverter.cs new file mode 100644 index 00000000000..0406b85ecc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class VersionInfoTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return VersionInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return VersionInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return VersionInfo.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.cs new file mode 100644 index 00000000000..a2cbce679ea --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.cs @@ -0,0 +1,84 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Next version definition. + public partial class VersionInfo : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfoInternal + { + + /// Backing field for property. + private string _latestVersion; + + /// Current latest version of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public string LatestVersion { get => this._latestVersion; set => this._latestVersion = value; } + + /// Backing field for property. + private long? _nextVersion; + + /// + /// Next version as defined by the server. The server keeps track of all versions that are string-representations of integers. + /// If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion + /// will default to '1'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Origin(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.PropertyOrigin.Owned)] + public long? NextVersion { get => this._nextVersion; set => this._nextVersion = value; } + + /// Creates an new instance. + public VersionInfo() + { + + } + } + /// Next version definition. + public partial interface IVersionInfo : + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IJsonSerializable + { + /// Current latest version of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Current latest version of the resource.", + SerializedName = @"latestVersion", + PossibleTypes = new [] { typeof(string) })] + string LatestVersion { get; set; } + /// + /// Next version as defined by the server. The server keeps track of all versions that are string-representations of integers. + /// If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion + /// will default to '1'. + /// + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Next version as defined by the server. The server keeps track of all versions that are string-representations of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion will default to '1'.", + SerializedName = @"nextVersion", + PossibleTypes = new [] { typeof(long) })] + long? NextVersion { get; set; } + + } + /// Next version definition. + internal partial interface IVersionInfoInternal + + { + /// Current latest version of the resource. + string LatestVersion { get; set; } + /// + /// Next version as defined by the server. The server keeps track of all versions that are string-representations of integers. + /// If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion + /// will default to '1'. + /// + long? NextVersion { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.json.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.json.cs new file mode 100644 index 00000000000..998b87c2900 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/api/Models/VersionInfo.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + + /// Next version definition. + public partial class VersionInfo + { + + /// + /// 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.MachineLearningServices.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json ? new VersionInfo(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.MachineLearningServices.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._nextVersion ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNumber((long)this._nextVersion) : null, "nextVersion" ,container.Add ); + AddIf( null != (((object)this._latestVersion)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonString(this._latestVersion.ToString()) : null, "latestVersion" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject instance to deserialize from. + internal VersionInfo(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nextVersion = If( json?.PropertyT("nextVersion"), out var __jsonNextVersion) ? (long?)__jsonNextVersion : _nextVersion;} + {_latestVersion = If( json?.PropertyT("latestVersion"), out var __jsonLatestVersion) ? (string)__jsonLatestVersion : (string)_latestVersion;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_Get.cs new file mode 100644 index 00000000000..444ef6026fd --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_Get.cs @@ -0,0 +1,535 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] GetLatest=>GET:"/indexes/{name}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndexLatest_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get latest version of the Index. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndexLatest_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndexLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesGetLatest(Name, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_GetViaIdentity.cs new file mode 100644 index 00000000000..84bfbf8fa34 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_GetViaIdentity.cs @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get latest version of the Index. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] GetLatest=>GET:"/indexes/{name}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndexLatest_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get latest version of the Index. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndexLatest_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndexLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IndexesGetLatestViaIdentity(InputObject.Id, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IndexesGetLatest(InputObject.Name ?? null, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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,WorkspaceName=WorkspaceName,Endpoint=Endpoint}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_List.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_List.cs new file mode 100644 index 00000000000..d8c28b3a73f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexLatest_List.cs @@ -0,0 +1,590 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// List the latest version of each index. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] ListLatest=>GET:"/indexes/" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndexLatest_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"List the latest version of each index. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndexLatest_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private int _maxpagesize; + + /// The maximum number of result items per page. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The maximum number of result items per page.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The maximum number of result items per page.", + SerializedName = @"maxpagesize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Maxpagesize { get => this._maxpagesize; set => this._maxpagesize = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private int _skip; + + /// The number of result items to skip. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to skip.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to skip.", + SerializedName = @"skip", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Skip { get => this._skip; set => this._skip = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private int _top; + + /// The number of result items to return. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to return.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to return.", + SerializedName = @"top", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Top { get => this._top; set => this._top = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndexLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesListLatest(this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?), Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Top=this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?),Skip=this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?),Maxpagesize=this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?)}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex + /// 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.MachineLearningServices.Models.IPagedIndex + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesListLatest_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_Get.cs new file mode 100644 index 00000000000..3628409d83b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_Get.cs @@ -0,0 +1,540 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// [OpenAPI] GetNextVersion=>POST:"/indexes/{name}:getNextVersion" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndexNextVersion_Get", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get next Index version as defined by the server. The server keeps track of all versions that are string-representations of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion will default to '1'.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}:getNextVersion", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndexNextVersion_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndexNextVersion_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesGetNextVersion' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesGetNextVersion(Name, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// 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.MachineLearningServices.Models.IVersionInfo + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_GetViaIdentity.cs new file mode 100644 index 00000000000..0cf683ad919 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndexNextVersion_GetViaIdentity.cs @@ -0,0 +1,546 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get next Index version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// [OpenAPI] GetNextVersion=>POST:"/indexes/{name}:getNextVersion" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndexNextVersion_GetViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get next Index version as defined by the server. The server keeps track of all versions that are string-representations of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion will default to '1'.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}:getNextVersion", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndexNextVersion_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndexNextVersion_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesGetNextVersion' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IndexesGetNextVersionViaIdentity(InputObject.Id, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IndexesGetNextVersion(InputObject.Name ?? null, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// 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.MachineLearningServices.Models.IVersionInfo + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_Get.cs new file mode 100644 index 00000000000..b6387c2d691 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_Get.cs @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of an Index. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndex_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of an Index.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndex_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndex_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesGet(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentity.cs new file mode 100644 index 00000000000..5862261a635 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentity.cs @@ -0,0 +1,543 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of an Index. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndex_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of an Index.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndex_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndex_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IndexesGetViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IndexesGet(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentityIndex.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentityIndex.cs new file mode 100644 index 00000000000..0bca392a716 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_GetViaIdentityIndex.cs @@ -0,0 +1,554 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of an Index. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndex_GetViaIdentityIndex")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of an Index.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndex_GetViaIdentityIndex : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _indexInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity IndexInputObject { get => this._indexInputObject; set => this._indexInputObject = 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndex_GetViaIdentityIndex() + { + + } + + /// 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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (IndexInputObject?.Id != null) + { + this.IndexInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + await this.Client.IndexesGetViaIdentity(IndexInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == IndexInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("IndexInputObject has null value for IndexInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, IndexInputObject) ); + } + await this.Client.IndexesGet(IndexInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_List.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_List.cs new file mode 100644 index 00000000000..a0ed94831d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspaceIndex_List.cs @@ -0,0 +1,648 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// List the versions of an Index given the name. + /// + /// [OpenAPI] List=>GET:"/indexes/{name}/versions" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspaceIndex_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"List the versions of an Index given the name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspaceIndex_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _listViewType; + + /// View type for including/excluding (for example) archived entities. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "View type for including/excluding (for example) archived entities.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"View type for including/excluding (for example) archived entities.", + SerializedName = @"listViewType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string ListViewType { get => this._listViewType; set => this._listViewType = value; } + + /// Backing field for property. + private int _maxpagesize; + + /// The maximum number of result items per page. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The maximum number of result items per page.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The maximum number of result items per page.", + SerializedName = @"maxpagesize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Maxpagesize { get => this._maxpagesize; set => this._maxpagesize = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _orderby; + + /// + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt'].")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt'].", + SerializedName = @"orderby", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string Orderby { get => this._orderby; set => this._orderby = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private int _skip; + + /// The number of result items to skip. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to skip.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to skip.", + SerializedName = @"skip", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Skip { get => this._skip; set => this._skip = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _tag; + + /// + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string Tag { get => this._tag; set => this._tag = value; } + + /// Backing field for property. + private int _top; + + /// The number of result items to return. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to return.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to return.", + SerializedName = @"top", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Top { get => this._top; set => this._top = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspaceIndex_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesList(Name, ListViewType, this.InvocationInformation.BoundParameters.ContainsKey("Orderby") ? Orderby : null, this.InvocationInformation.BoundParameters.ContainsKey("Tag") ? Tag : null, this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?), SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,ListViewType=ListViewType,Orderby=this.InvocationInformation.BoundParameters.ContainsKey("Orderby") ? Orderby : null,Tag=this.InvocationInformation.BoundParameters.ContainsKey("Tag") ? Tag : null,Top=this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?),Skip=this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?),Maxpagesize=this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?)}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedIndex + /// 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.MachineLearningServices.Models.IPagedIndex + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_Get.cs new file mode 100644 index 00000000000..de43fa11ca2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_Get.cs @@ -0,0 +1,535 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] GetLatest=>GET:"/prompts/{name}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePromptLatest_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get latest version of the Prompt. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePromptLatest_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePromptLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsGetLatest(Name, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_GetViaIdentity.cs new file mode 100644 index 00000000000..8f2e3c5ed7e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_GetViaIdentity.cs @@ -0,0 +1,541 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get latest version of the Prompt. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] GetLatest=>GET:"/prompts/{name}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePromptLatest_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get latest version of the Prompt. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePromptLatest_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePromptLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PromptsGetLatestViaIdentity(InputObject.Id, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PromptsGetLatest(InputObject.Name ?? null, SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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,WorkspaceName=WorkspaceName,Endpoint=Endpoint}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_List.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_List.cs new file mode 100644 index 00000000000..6708da3602a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptLatest_List.cs @@ -0,0 +1,590 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// List the latest version of each prompt. Latest is defined by most recent created by date. + /// + /// + /// [OpenAPI] ListLatest=>GET:"/prompts/" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePromptLatest_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"List the latest version of each prompt. Latest is defined by most recent created by date.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePromptLatest_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private int _maxpagesize; + + /// The maximum number of result items per page. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The maximum number of result items per page.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The maximum number of result items per page.", + SerializedName = @"maxpagesize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Maxpagesize { get => this._maxpagesize; set => this._maxpagesize = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private int _skip; + + /// The number of result items to skip. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to skip.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to skip.", + SerializedName = @"skip", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Skip { get => this._skip; set => this._skip = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private int _top; + + /// The number of result items to return. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to return.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to return.", + SerializedName = @"top", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Top { get => this._top; set => this._top = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePromptLatest_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsListLatest(this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?), Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Top=this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?),Skip=this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?),Maxpagesize=this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?)}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt + /// 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.MachineLearningServices.Models.IPagedPrompt + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsListLatest_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_Get.cs new file mode 100644 index 00000000000..7867aaf660a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_Get.cs @@ -0,0 +1,540 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// [OpenAPI] GetNextVersion=>POST:"/prompts/{name}:getNextVersion" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePromptNextVersion_Get", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion will default to '1'.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}:getNextVersion", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePromptNextVersion_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePromptNextVersion_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsGetNextVersion' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsGetNextVersion(Name, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Name=Name}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// 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.MachineLearningServices.Models.IVersionInfo + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_GetViaIdentity.cs new file mode 100644 index 00000000000..436670d0468 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePromptNextVersion_GetViaIdentity.cs @@ -0,0 +1,546 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// + /// Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations + /// of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, + /// the nextVersion will default to '1'. + /// + /// + /// [OpenAPI] GetNextVersion=>POST:"/prompts/{name}:getNextVersion" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePromptNextVersion_GetViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get next Prompt version as defined by the server. The server keeps track of all versions that are string-representations of integers. If one exists, the nextVersion will be a string representation of the highest integer value + 1. Otherwise, the nextVersion will default to '1'.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}:getNextVersion", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePromptNextVersion_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePromptNextVersion_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsGetNextVersion' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PromptsGetNextVersionViaIdentity(InputObject.Id, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PromptsGetNextVersion(InputObject.Name ?? null, Endpoint, SubscriptionId, ResourceGroupName, WorkspaceName, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Endpoint=Endpoint,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IVersionInfo + /// 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.MachineLearningServices.Models.IVersionInfo + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_Get.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_Get.cs new file mode 100644 index 00000000000..b06881a43a6 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_Get.cs @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of a Prompt. + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePrompt_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of a Prompt.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePrompt_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePrompt_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsGet(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentity.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentity.cs new file mode 100644 index 00000000000..6541126c869 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentity.cs @@ -0,0 +1,543 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of a Prompt. + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePrompt_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of a Prompt.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePrompt_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePrompt_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PromptsGetViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PromptsGet(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentityPrompt.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentityPrompt.cs new file mode 100644 index 00000000000..e88178fe324 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_GetViaIdentityPrompt.cs @@ -0,0 +1,554 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// Get a specific version of a Prompt. + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePrompt_GetViaIdentityPrompt")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"Get a specific version of a Prompt.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePrompt_GetViaIdentityPrompt : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _promptInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity PromptInputObject { get => this._promptInputObject; set => this._promptInputObject = 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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePrompt_GetViaIdentityPrompt() + { + + } + + /// 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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (PromptInputObject?.Id != null) + { + this.PromptInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + await this.Client.PromptsGetViaIdentity(PromptInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == PromptInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("PromptInputObject has null value for PromptInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, PromptInputObject) ); + } + await this.Client.PromptsGet(PromptInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_List.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_List.cs new file mode 100644 index 00000000000..1db9b7006e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/GetAzMlWorkspacePrompt_List.cs @@ -0,0 +1,648 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// List the versions of a Prompt given the name. + /// + /// [OpenAPI] List=>GET:"/prompts/{name}/versions" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzMlWorkspacePrompt_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"List the versions of a Prompt given the name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions", ApiVersion = "2024-05-01-preview")] + public partial class GetAzMlWorkspacePrompt_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _listViewType; + + /// View type for including/excluding (for example) archived entities. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "View type for including/excluding (for example) archived entities.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"View type for including/excluding (for example) archived entities.", + SerializedName = @"listViewType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string ListViewType { get => this._listViewType; set => this._listViewType = value; } + + /// Backing field for property. + private int _maxpagesize; + + /// The maximum number of result items per page. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The maximum number of result items per page.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The maximum number of result items per page.", + SerializedName = @"maxpagesize", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Maxpagesize { get => this._maxpagesize; set => this._maxpagesize = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// Backing field for property. + private string _orderby; + + /// + /// Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt']. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt'].")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Ordering of list: Please choose orderby value from ['createdAt', 'lastModifiedAt'].", + SerializedName = @"orderby", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string Orderby { get => this._orderby; set => this._orderby = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Backing field for property. + private int _skip; + + /// The number of result items to skip. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to skip.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to skip.", + SerializedName = @"skip", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Skip { get => this._skip; set => this._skip = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _tag; + + /// + /// Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Comma-separated list of tag names (and optionally values). Example: tag1,tag2=value2.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public string Tag { get => this._tag; set => this._tag = value; } + + /// Backing field for property. + private int _top; + + /// The number of result items to return. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The number of result items to return.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"The number of result items to return.", + SerializedName = @"top", + PossibleTypes = new [] { typeof(int) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Query)] + public int Top { get => this._top; set => this._top = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzMlWorkspacePrompt_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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsList(Name, ListViewType, this.InvocationInformation.BoundParameters.ContainsKey("Orderby") ? Orderby : null, this.InvocationInformation.BoundParameters.ContainsKey("Tag") ? Tag : null, this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?), this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?), SubscriptionId, ResourceGroupName, WorkspaceName, Endpoint, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,ListViewType=ListViewType,Orderby=this.InvocationInformation.BoundParameters.ContainsKey("Orderby") ? Orderby : null,Tag=this.InvocationInformation.BoundParameters.ContainsKey("Tag") ? Tag : null,Top=this.InvocationInformation.BoundParameters.ContainsKey("Top") ? Top : default(int?),Skip=this.InvocationInformation.BoundParameters.ContainsKey("Skip") ? Skip : default(int?),Maxpagesize=this.InvocationInformation.BoundParameters.ContainsKey("Maxpagesize") ? Maxpagesize : default(int?)}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPagedPrompt + /// 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.MachineLearningServices.Models.IPagedPrompt + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsList_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateExpanded.cs new file mode 100644 index 00000000000..ea766a4be9e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateExpanded.cs @@ -0,0 +1,667 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspaceIndex_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspaceIndex_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspaceIndex_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..a8149d363fe --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityExpanded.cs @@ -0,0 +1,663 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspaceIndex_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspaceIndex_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspaceIndex_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.IndexesCreateOrUpdateViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.IndexesCreateOrUpdate(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityIndexExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityIndexExpanded.cs new file mode 100644 index 00000000000..ef18da4f123 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaIdentityIndexExpanded.cs @@ -0,0 +1,674 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspaceIndex_CreateViaIdentityIndexExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspaceIndex_CreateViaIdentityIndexExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _indexInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity IndexInputObject { get => this._indexInputObject; set => this._indexInputObject = 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspaceIndex_CreateViaIdentityIndexExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (IndexInputObject?.Id != null) + { + this.IndexInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + await this.Client.IndexesCreateOrUpdateViaIdentity(IndexInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == IndexInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("IndexInputObject has null value for IndexInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, IndexInputObject) ); + } + await this.Client.IndexesCreateOrUpdate(IndexInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..e6d249f733b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonFilePath.cs @@ -0,0 +1,617 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspaceIndex_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class NewAzMlWorkspaceIndex_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspaceIndex_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonString.cs new file mode 100644 index 00000000000..771e1a573fd --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspaceIndex_CreateViaJsonString.cs @@ -0,0 +1,615 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspaceIndex_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class NewAzMlWorkspaceIndex_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspaceIndex_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateExpanded.cs new file mode 100644 index 00000000000..6005027fcd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateExpanded.cs @@ -0,0 +1,678 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspacePrompt_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspacePrompt_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspacePrompt_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..c890495b2b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityExpanded.cs @@ -0,0 +1,674 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspacePrompt_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspacePrompt_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspacePrompt_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.PromptsCreateOrUpdateViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.PromptsCreateOrUpdate(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityPromptExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityPromptExpanded.cs new file mode 100644 index 00000000000..1863a85749b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaIdentityPromptExpanded.cs @@ -0,0 +1,685 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspacePrompt_CreateViaIdentityPromptExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class NewAzMlWorkspacePrompt_CreateViaIdentityPromptExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _promptInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity PromptInputObject { get => this._promptInputObject; set => this._promptInputObject = value; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspacePrompt_CreateViaIdentityPromptExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (PromptInputObject?.Id != null) + { + this.PromptInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + await this.Client.PromptsCreateOrUpdateViaIdentity(PromptInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == PromptInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("PromptInputObject has null value for PromptInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, PromptInputObject) ); + } + await this.Client.PromptsCreateOrUpdate(PromptInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..de3cf1ef6d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonFilePath.cs @@ -0,0 +1,617 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspacePrompt_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class NewAzMlWorkspacePrompt_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspacePrompt_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonString.cs new file mode 100644 index 00000000000..9fb3f33d024 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/NewAzMlWorkspacePrompt_CreateViaJsonString.cs @@ -0,0 +1,615 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// create a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzMlWorkspacePrompt_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"create a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class NewAzMlWorkspacePrompt_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzMlWorkspacePrompt_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateExpanded.cs new file mode 100644 index 00000000000..13cceb95120 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateExpanded.cs @@ -0,0 +1,668 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspaceIndex_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class SetAzMlWorkspaceIndex_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspaceIndex_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..b1136296303 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonFilePath.cs @@ -0,0 +1,618 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspaceIndex_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class SetAzMlWorkspaceIndex_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspaceIndex_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonString.cs new file mode 100644 index 00000000000..9b2201b3b06 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspaceIndex_UpdateViaJsonString.cs @@ -0,0 +1,616 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspaceIndex_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/indexes/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class SetAzMlWorkspaceIndex_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.IndexesCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspaceIndex_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateExpanded.cs new file mode 100644 index 00000000000..900b166a814 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateExpanded.cs @@ -0,0 +1,679 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspacePrompt_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + public partial class SetAzMlWorkspacePrompt_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspacePrompt_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..a6bfc40fd9a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonFilePath.cs @@ -0,0 +1,618 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspacePrompt_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class SetAzMlWorkspacePrompt_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspacePrompt_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonString.cs new file mode 100644 index 00000000000..fce5995353e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/SetAzMlWorkspacePrompt_UpdateViaJsonString.cs @@ -0,0 +1,616 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzMlWorkspacePrompt_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.HttpPath(Path = "/prompts/{name}/versions/{version}", ApiVersion = "2024-05-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.NotSuggestDefaultParameterSet] + public partial class SetAzMlWorkspacePrompt_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.PromptsCreateOrUpdateViaJsonString(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _jsonString, onCreated, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzMlWorkspacePrompt_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateExpanded.cs new file mode 100644 index 00000000000..c0c4c3e3674 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateExpanded.cs @@ -0,0 +1,693 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspaceIndex_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspaceIndex_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the index.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _body = await this.Client.IndexesGetWithResult(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.IndexesCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspaceIndex_UpdateExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StorageUri"))) + { + this.StorageUri = (string)(this.MyInvocation?.BoundParameters["StorageUri"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..6937bdc93d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityExpanded.cs @@ -0,0 +1,691 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspaceIndex_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspaceIndex_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _body = await this.Client.IndexesGetViaIdentityWithResult(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.IndexesCreateOrUpdateViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _body = await this.Client.IndexesGetWithResult(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.IndexesCreateOrUpdate(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspaceIndex_UpdateViaIdentityExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StorageUri"))) + { + this.StorageUri = (string)(this.MyInvocation?.BoundParameters["StorageUri"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded.cs new file mode 100644 index 00000000000..b1514978c27 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded.cs @@ -0,0 +1,702 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a IndexVersion. + /// + /// [OpenAPI] Get=>GET:"/indexes/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/indexes/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a IndexVersion.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Index resource Definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Index(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _indexInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity IndexInputObject { get => this._indexInputObject; set => this._indexInputObject = 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = value; } + + /// + /// Default workspace blob storage Uri. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Uri. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Uri. Should work across storage types and auth scenarios.", + SerializedName = @"storageUri", + PossibleTypes = new [] { typeof(string) })] + public string StorageUri { get => _body.StorageUri ?? null; set => _body.StorageUri = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Backing field for property. + private string _version; + + /// Version of the index. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the index.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the index.", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'IndexesCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (IndexInputObject?.Id != null) + { + this.IndexInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + _body = await this.Client.IndexesGetViaIdentityWithResult(IndexInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.IndexesCreateOrUpdateViaIdentity(IndexInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == IndexInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("IndexInputObject has null value for IndexInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, IndexInputObject) ); + } + _body = await this.Client.IndexesGetWithResult(IndexInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.IndexesCreateOrUpdate(IndexInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspaceIndex_UpdateViaIdentityIndexExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StorageUri"))) + { + this.StorageUri = (string)(this.MyInvocation?.BoundParameters["StorageUri"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IIndex + /// 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.MachineLearningServices.Models.IIndex + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateExpanded.cs new file mode 100644 index 00000000000..bc04d133c96 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateExpanded.cs @@ -0,0 +1,708 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspacePrompt_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspacePrompt_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the prompt", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _body = await this.Client.PromptsGetWithResult(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.PromptsCreateOrUpdate(Name, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Name=Name,Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspacePrompt_UpdateExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DataUri"))) + { + this.DataUri = (string)(this.MyInvocation?.BoundParameters["DataUri"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TemplatePath"))) + { + this.TemplatePath = (string)(this.MyInvocation?.BoundParameters["TemplatePath"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..f003a24e0a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityExpanded.cs @@ -0,0 +1,706 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspacePrompt_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspacePrompt_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity 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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _body = await this.Client.PromptsGetViaIdentityWithResult(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.PromptsCreateOrUpdateViaIdentity(InputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == InputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.Version) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.Version"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _body = await this.Client.PromptsGetWithResult(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.PromptsCreateOrUpdate(InputObject.Name ?? null, InputObject.Version ?? null, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspacePrompt_UpdateViaIdentityExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DataUri"))) + { + this.DataUri = (string)(this.MyInvocation?.BoundParameters["DataUri"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TemplatePath"))) + { + this.TemplatePath = (string)(this.MyInvocation?.BoundParameters["TemplatePath"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded.cs new file mode 100644 index 00000000000..15ff17514fc --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/cmdlets/UpdateAzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded.cs @@ -0,0 +1,717 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets; + using System; + + /// update a Prompt + /// + /// [OpenAPI] Get=>GET:"/prompts/{name}/versions/{version}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/prompts/{name}/versions/{version}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt))] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Description(@"update a Prompt")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Generated] + public partial class UpdateAzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Prompt resource definition + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt _body = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.Prompt(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.ClientAPI; + + /// + /// Default workspace blob storage Ui. Should work across storage types and auth scenarios. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Default workspace blob storage Ui. Should work across storage types and auth scenarios.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Default workspace blob storage Ui. Should work across storage types and auth scenarios.", + SerializedName = @"dataUri", + PossibleTypes = new [] { typeof(string) })] + public string DataUri { get => _body.DataUri ?? null; set => _body.DataUri = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Description information of the asset. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Description information of the asset.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Description information of the asset.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + public string Description { get => _body.Description ?? null; set => _body.Description = value; } + + /// Backing field for property. + private string _endpoint; + + /// Supported Azure-AI asset endpoints. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Supported Azure-AI asset endpoints.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Supported Azure-AI asset endpoints.", + SerializedName = @"endpoint", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string Endpoint { get => this._endpoint; set => this._endpoint = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity _promptInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IMachineLearningServicesIdentity PromptInputObject { get => this._promptInputObject; set => this._promptInputObject = value; } + + /// + /// Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's properties. Unlike tags, properties are add-only. Once added, a property cannot be removed.", + SerializedName = @"properties", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Property { get => _body.Property ?? null /* object */; set => _body.Property = value; } + + /// The URI for the proxy server to use + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the Resource Group.", + SerializedName = @"resourceGroupName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// + /// Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development. + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Update stage to 'Archive' to archive the asset. Default is Development, which means the asset is under development.", + SerializedName = @"stage", + PossibleTypes = new [] { typeof(string) })] + public string Stage { get => _body.Stage ?? null; set => _body.Stage = 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.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Asset's tags. Unlike properties, tags are fully mutable. + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Asset's tags. Unlike properties, tags are fully mutable.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Asset's tags. Unlike properties, tags are fully mutable.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags Tag { get => _body.Tag ?? null /* object */; set => _body.Tag = value; } + + /// Relative path of the prompt data file at the dataUri location + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Relative path of the prompt data file at the dataUri location")] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Relative path of the prompt data file at the dataUri location", + SerializedName = @"templatePath", + PossibleTypes = new [] { typeof(string) })] + public string TemplatePath { get => _body.TemplatePath ?? null; set => _body.TemplatePath = value; } + + /// Backing field for property. + private string _version; + + /// Version of the prompt + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Version of the prompt")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Version of the prompt", + SerializedName = @"version", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Path)] + public string Version { get => this._version; set => this._version = value; } + + /// Backing field for property. + private string _workspaceName; + + /// The name of the AzureML workspace or AI project. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the AzureML workspace or AI project.")] + [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The name of the AzureML workspace or AI project.", + SerializedName = @"workspaceName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Category(global::Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.ParameterCategory.Uri)] + public string WorkspaceName { get => this._workspaceName; set => this._workspaceName = 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 Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onCreated method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnCreated(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'PromptsCreateOrUpdate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (PromptInputObject?.Id != null) + { + this.PromptInputObject.Id += $"/versions/{(global::System.Uri.EscapeDataString(this.Version.ToString()))}"; + _body = await this.Client.PromptsGetViaIdentityWithResult(PromptInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.PromptsCreateOrUpdateViaIdentity(PromptInputObject.Id, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == PromptInputObject.Name) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("PromptInputObject has null value for PromptInputObject.Name"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, PromptInputObject) ); + } + _body = await this.Client.PromptsGetWithResult(PromptInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, this, Pipeline); + this.Update_body(); + await this.Client.PromptsCreateOrUpdate(PromptInputObject.Name ?? null, Version, ResourceGroupName, WorkspaceName, Endpoint, SubscriptionId, _body, onCreated, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { Version=Version,ResourceGroupName=ResourceGroupName,WorkspaceName=WorkspaceName,Endpoint=Endpoint,SubscriptionId=SubscriptionId}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzMlWorkspacePrompt_UpdateViaIdentityPromptExpanded() + { + + } + + private void Update_body() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Stage"))) + { + this.Stage = (string)(this.MyInvocation?.BoundParameters["Stage"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Description"))) + { + this.Description = (string)(this.MyInvocation?.BoundParameters["Description"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Property"))) + { + this.Property = (Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.ITags)(this.MyInvocation?.BoundParameters["Property"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DataUri"))) + { + this.DataUri = (string)(this.MyInvocation?.BoundParameters["DataUri"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("TemplatePath"))) + { + this.TemplatePath = (string)(this.MyInvocation?.BoundParameters["TemplatePath"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// a delegate that is called when the remote service returns 201 (Created). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Models.IPrompt + /// 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.MachineLearningServices.Models.IPrompt + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..319d64d44a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this cmdlet"); + } + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..5ad28f6a675 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..edd18743649 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to a type + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..9ae8be3fa10 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/ExternalDocsAttribute.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..95752bdc29e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..5afd7e95d5e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..e3e463906fd --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..dbe21a55008 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..ad7951c440c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..349eb9b22ca --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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.MachineLearningServices.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..f3f4d5950ce --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.HasAllowEmptyArray.ToAllowEmptyArray()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..80eb929c4f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.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.MachineLearningServices.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: MachineLearningServices cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.MachineLearningServices.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.MachineLearningServices.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = '{previewVersion}'"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule MachineLearningServices".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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..f140f94b5d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + /*var loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + + + + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + sb.AppendLine(@"{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath)" + ); + sb.AppendLine($@" $TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@" $currentPath = $PSScriptRoot + while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent + } + . ($mockingPath | Select-Object -First 1).FullName +} +"); + + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..3a527d76a57 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..45ed381fe13 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..7889fd57b1e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..5eec639d408 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..dfded3741ee --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"[{relatedLink}]({relatedLink}){Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..e97afd9a422 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..6b474bc1296 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + ExampleInfo.Description.ToDescriptionFormat()); ; + } + } + } + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://learn.microsoft.com/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Synopsis.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + public const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..2f9b4b5ce9a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..ab66a28a5b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && !pg.Parameters.All(p => p.IsHidden())) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (codeEndIndex ?? 0)) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, output, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow && !p.IsHidden()).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..473be19c469 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{Environment.NewLine}" : String.Empty; + } + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText}{externalUrlsText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new[] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new[] { "
", "\r\n", "\n" }); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..5bde01eef1f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + + public string RootModuleName { get => @""; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + if (variantParamCountGroups.Length == 0) + { + variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + } + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public bool IsNotSuggestDefaultParameterSet { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + IsNotSuggestDefaultParameterSet = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public bool HasAllowEmptyArray { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + public PSArgumentCompleterAttribute PSArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}"; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines(); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[] { } : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => (!ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + public static PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(completerAttribute); + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..b6708f925f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class ConstantAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..548c3778b0e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..eef9da8020a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,105 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.TrimStart().StartsWith(GuidStart.TrimStart()))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..6f55b72138d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..74921e84689 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..acd99d9864e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..9f187d47a68 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.MachineLearningServices Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..019ea7485ad --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..2cb46dee910 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..b8596965fe0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..acfad9571ed --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..f5e605857cb --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..5c492ab1d4d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..3e138fca77d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..5d5a4c8d0f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..0b308585d20 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..e2a59e25a61 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..5b32465d88b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..21a23407837 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..332323e2373 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..185c69eef65 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..5bf0369a8c0 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..dca92a8fac8 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..ee5ed643370 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..80f1efc2f08 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..c52f67c082d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..f7dd7f9aacd --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..8391fcdcc36 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..6bc0fe5544e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..e9f55002d7a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..ee7e3041f2c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..780bafcb667 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..080d91a247f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..1da2f006a40 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..3df2201cdd3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.JsonSerializable.ToJson(dict, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..c27f45ea1d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..9488b22fb52 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..72c06463748 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..02e27c4c3b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..382593b60a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..c7a94c6469a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..fd8206bb947 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..0cb84d5ac5f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..3687b091500 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..86a5ea26e74 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..6c5723f0604 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime +{ + using System; + + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..50acf929af7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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.MachineLearningServices.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..a0013138b8d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + public const string Progress = nameof(Progress); + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..e89e36c460d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..49f7d7b02ee --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Extensions.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..05d73943950 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..fd9d1d77044 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..ca035b427cf --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..e291614c186 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..bd79860564c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..708e400f659 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..9e3647dfaca --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..b2b77eeb834 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..519c4b6df80 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..48f8260214a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/ISendAsync.cs @@ -0,0 +1,413 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private const int DefaultMaxRetry = 3; + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..752f7c1053d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..9ee7a56a62c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..0eff26bfb44 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..8859934a207 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..7a2379a1e82 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..93e31039eca --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..3cf02c8ecf3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..0d3e344cfe5 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..2fabf307377 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..0b524528b7d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..f0389d02542 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..3f8e8a15b5e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..a44ec590384 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..13a8f31eb2b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + internal XNodeArray(System.Collections.Generic.List values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..75bbec3367e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..cfb838c29d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..43917d2a4b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..368eecc057f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..c957b1628b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..ee5d1342378 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..ab995327953 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..cb89f5a46de --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..0178202ae64 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..5c0b9b961f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..e52d93e7584 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..9b7433c350b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..51aa7688a2c --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..75eafbe8b61 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..508c15cfb00 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..7421cfb7772 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..fd3213d6c08 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"), isBase64Request)) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..fe18ab94449 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..a08a2e50172 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..3435ef74525 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..ba81ba8a93a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..b840f4ef8d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..85f139b1308 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..746951d038b --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/SerializationMode.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..22e9d400986 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.List SelectToList(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }.ToList(); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0].ToList(); // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result; + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..7f3a6f9d90f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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.MachineLearningServices.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // see if there is an error block in the body + json = json?.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..1f641a9a460 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/AzureAI.Assets/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..7d304e80c9d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/how-to.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/how-to.md new file mode 100644 index 00000000000..f0b50a79582 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.MachineLearningServices`. + +## Building `Az.MachineLearningServices` +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.MachineLearningServices` +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.MachineLearningServices` +To pack `Az.MachineLearningServices` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.MachineLearningServices`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.MachineLearningServices.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.MachineLearningServices.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.MachineLearningServices`. + - `-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.MachineLearningServices` 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/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/Az.MachineLearningServices.internal.psm1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/Az.MachineLearningServices.internal.psm1 new file mode 100644 index 00000000000..f7cabacbf0d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/Az.MachineLearningServices.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.MachineLearningServices.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/README.md new file mode 100644 index 00000000000..31e7cf71592 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/internal/README.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.MachineLearningServices.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.MachineLearningServices`. Instead, this sub-module is imported by the `..\custom\Az.MachineLearningServices.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.MachineLearningServices.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.MachineLearningServices`. diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/license.txt b/tests-upgrade/tests-emitter/AzureAI.Assets/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/license.txt @@ -0,0 +1,227 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + + +The software includes the AutoMapper library ("AutoMapper"). The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Provided for Informational Purposes Only + +AutoMapper + +The MIT License (MIT) +Copyright (c) 2010 Jimmy Bogard + + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + +*************** + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/pack-module.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/resources/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/run-module.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/run-module.ps1 new file mode 100644 index 00000000000..9177e5910f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MachineLearningServices.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/tests-upgrade/tests-emitter/AzureAI.Assets/target/test-module.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/test-module.ps1 new file mode 100644 index 00000000000..84da20f93c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) +{ + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.MachineLearningServices.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/test/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/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/tests-upgrade/tests-emitter/AzureAI.Assets/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/README.md new file mode 100644 index 00000000000..cdaf3a995a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/README.md @@ -0,0 +1,438 @@ + +# Az.Resources.TestSupport +This directory contains the PowerShell module for the Resources service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Resources.TestSupport`, 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
`npm install -g 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` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +> Values +``` yaml +azure: true +powershell: true +branch: master +repo: https://github.com/Azure/azure-rest-api-specs/blob/$(branch) +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + copyright: Microsoft Corporation. All rights reserved. + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell +``` + +> Names +``` yaml +prefix: Az +``` + +> Folders +``` yaml +clear-output-folder: true +``` + +``` yaml +input-file: + - $(repo)/specification/resources/resource-manager/Microsoft.Resources/stable/2018-05-01/resources.json +module-name: Az.Resources.TestSupport +namespace: Microsoft.Azure.PowerShell.Cmdlets.Resources + +subject-prefix: '' +module-version: 0.0.1 +title: Resources + +directive: + - remove-operation: Deployments_CreateOrUpdateAtSubscriptionScope + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - from: swagger-document + where: $..parameters[?(@.name=='$filter')] + transform: $['x-ms-skip-url-encoding'] = true + - from: swagger-document + where: $..[?( /Resources_(CreateOrUpdate|Update|Delete|Get|GetById|CheckExistence|CheckExistenceById)/g.exec(@.operationId))] + transform: "$.parameters = $.parameters.map( each => { each.name = each.name === 'api-version' ? 'explicit-api-version' : each.name; return each; } );" + - from: source-file-csharp + where: $ + transform: $ = $.replace(/explicit-api-version/g, 'api-version'); + - where: + parameter-name: ExplicitApiVersion + set: + parameter-name: ApiVersion + - from: source-file-csharp + where: $ + transform: > + $ = $.replace(/result.OdataNextLink/g,'nextLink' ); + return $.replace( /(^\s*)(if\s*\(\s*nextLink\s*!=\s*null\s*\))/gm, '$1var nextLink = Module.Instance.FixNextLink(responseMessage, result.OdataNextLink);\n$1$2' ); + - from: swagger-document + where: + - $..DeploymentProperties.properties.template + - $..DeploymentProperties.properties.parameters + - $..ResourceGroupExportResult.properties.template + - $..PolicyDefinitionProperties.properties.policyRule + transform: $.additionalProperties = true; + - where: + verb: Set + subject: Resource + remove: true + - where: + verb: Set + subject: Deployment + remove: true + - where: + subject: Resource + parameter-name: GroupName + set: + parameter-name: ResourceGroupName + clear-alias: true + - where: + subject: Resource + parameter-name: Id + set: + parameter-name: ResourceId + clear-alias: true + - where: + subject: Resource + parameter-name: Type + set: + parameter-name: ResourceType + clear-alias: true + - where: + subject: Appliance* + remove: true + - where: + verb: Test + subject: CheckNameAvailability + set: + subject: NameAvailability + - where: + verb: Export + subject: ResourceGroupTemplate + set: + subject: ResourceGroup + alias: Export-AzResourceGroupTemplate + - where: + parameter-name: Filter + set: + alias: ODataQuery + - where: + verb: Test + subject: ResourceGroupExistence + set: + subject: ResourceGroup + alias: Test-AzResourceGroupExistence + - where: + verb: Export + subject: DeploymentTemplate + set: + alias: [Save-AzDeploymentTemplate, Save-AzResourceGroupDeploymentTemplate] + - where: + subject: Deployment + set: + alias: ${verb}-AzResourceGroupDeployment + - where: + verb: Get + subject: DeploymentOperation + set: + alias: Get-AzResourceGroupDeploymentOperation + - where: + verb: New + subject: Deployment + variant: Create.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + hide: true + - where: + verb: Test + subject: Deployment + variant: Validate.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + parameter-name: DebugSettingDetailLevel + set: + parameter-name: DeploymentDebugLogLevel + - where: + subject: Provider + set: + subject: ResourceProvider + - where: + subject: ProviderFeature|ResourceProvider|ResourceLock + parameter-name: ResourceProviderNamespace + set: + alias: ProviderNamespace + - where: + verb: Update + subject: ResourceGroup + parameter-name: Name + clear-alias: true + - where: + parameter-name: UpnOrObjectId + set: + alias: ['UserPrincipalName', 'Upn', 'ObjectId'] + - where: + subject: Deployment + variant: (.*)Expanded(.*) + parameter-name: Parameter + set: + parameter-name: DeploymentParameter + # Format output + - where: + model-name: GenericResource + set: + format-table: + properties: + - Name + - ResourceGroupName + - Type + - Location + labels: + Type: ResourceType + - where: + model-name: ResourceGroup + set: + format-table: + properties: + - Name + - Location + - ProvisioningState + - where: + model-name: DeploymentExtended + set: + format-table: + properties: + - Name + - ProvisioningState + - Timestamp + - Mode + - where: + model-name: PolicyAssignment + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicyDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicySetDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: Provider + set: + format-table: + properties: + - Namespace + - RegistrationState + - where: + model-name: ProviderResourceType + set: + format-table: + properties: + - ResourceType + - Location + - ApiVersion + - where: + model-name: FeatureResult + set: + format-table: + properties: + - Name + - State + - where: + model-name: TagDetails + set: + format-table: + properties: + - TagName + - CountValue + - where: + model-name: Application + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppId + - Homepage + - AvailableToOtherTenant + - where: + model-name: KeyCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - Type + - where: + model-name: PasswordCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - where: + model-name: User + set: + format-table: + properties: + - PrincipalName + - DisplayName + - ObjectId + - Type + - where: + model-name: AdGroup + set: + format-table: + properties: + - DisplayName + - Mail + - ObjectId + - SecurityEnabled + - where: + model-name: ServicePrincipal + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppDisplayName + - AppId + - where: + model-name: Location + set: + format-table: + properties: + - Name + - DisplayName + - where: + model-name: ManagementLockObject + set: + format-table: + properties: + - Name + - Level + - ResourceId + - where: + model-name: RoleAssignment + set: + format-table: + properties: + - DisplayName + - ObjectId + - ObjectType + - RoleDefinitionName + - Scope + - where: + model-name: RoleDefinition + set: + format-table: + properties: + - RoleName + - Name + - Action +# To remove cmdlets not used in the test frame + - where: + subject: Operation + remove: true + - where: + subject: Deployment + variant: (.*)1|Cancel(.*)|Validate(.*)|Export(.*)|List(.*)|Delete(.*)|Check(.*)|Calculate(.*) + remove: true + - where: + subject: ResourceProvider + variant: Register(.*)|Unregister(.*)|Get(.*) + remove: true + - where: + subject: ResourceGroup + variant: List(.*)|Update(.*)|Export(.*)|Move(.*) + remove: true + - where: + subject: Resource + remove: true + - where: + subject: Tag|TagValue + remove: true + - where: + subject: DeploymentOperation + remove: true + - where: + subject: DeploymentTemplate + remove: true + - where: + subject: Calculate(.*) + remove: true + - where: + subject: ResourceExistence + remove: true + - where: + subject: ResourceMoveResource + remove: true + - where: + subject: DeploymentExistence + remove: true +``` diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/custom/New-AzDeployment.ps1 @@ -0,0 +1,231 @@ +function New-AzDeployment { + [OutputType('Microsoft.Azure.PowerShell.Cmdlets.Resources.Models.IDeploymentExtended')] + [CmdletBinding(DefaultParameterSetName='CreateWithTemplateFileParameterFile', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Description('You can provide the template and parameters directly in the request or link to JSON files.')] + param( + [Parameter(HelpMessage='The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name.')] + [Alias('DeploymentName')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='deploymentName', Required, PossibleTypes=([System.String]), Description='The name of the deployment.')] + [System.String] + # The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name. + ${Name}, + + [Parameter(Mandatory, HelpMessage='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='subscriptionId', Required, PossibleTypes=([System.String]), Description='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='resourceGroupName', Required, PossibleTypes=([System.String]), Description='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [System.String] + # The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [System.String] + # Local path to the JSON template file. + ${TemplateFile}, + + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [System.String] + # The string representation of the JSON template. + ${TemplateJson}, + + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the JSON template. + ${TemplateObject}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [System.String] + # Local path to the parameter JSON template file. + ${TemplateParameterFile}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [System.String] + # The string representation of the parameter JSON template. + ${TemplateParameterJson}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the parameter JSON template. + ${TemplateParameterObject}, + + [Parameter(Mandatory, HelpMessage='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode])] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='mode', Required, PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode]), Description='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode] + # The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. + ${Mode}, + + [Parameter(HelpMessage='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='detailLevel', PossibleTypes=([System.String]), Description='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [System.String] + # Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations. + ${DeploymentDebugLogLevel}, + + [Parameter(HelpMessage='The location to store the deployment data.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='location', PossibleTypes=([System.String]), Description='The location to store the deployment data.')] + [System.String] + # The location to store the deployment data. + ${Location}, + + [Parameter(HelpMessage='The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(HelpMessage='Run the command asynchronously')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait} + + ) + + process { + if ($PSBoundParameters.ContainsKey("TemplateFile")) + { + if (!(Test-Path -Path $TemplateFile)) + { + throw "Unable to find template file '$TemplateFile'." + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (Get-Item -Path $TemplateFile).BaseName + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + $TemplateJson = [System.IO.File]::ReadAllText($TemplateFile) + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateJson")) + { + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateObject")) + { + $TemplateJson = ConvertTo-Json -InputObject $TemplateObject + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateObject") + } + + if ($PSBoundParameters.ContainsKey("TemplateParameterFile")) + { + if (!(Test-Path -Path $TemplateParameterFile)) + { + throw "Unable to find template parameter file '$TemplateParameterFile'." + } + + $ParameterJson = [System.IO.File]::ReadAllText($TemplateParameterFile) + $ParameterObject = ConvertFrom-Json -InputObject $ParameterJson + $ParameterHashtable = @{} + $ParameterObject.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + $ParameterHashtable.Remove("`$schema") + $ParameterHashtable.Remove("contentVersion") + $NestedValues = $ParameterHashtable.parameters + if ($null -ne $NestedValues) + { + $ParameterHashtable.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + } + + $ParameterJson = ConvertTo-Json -InputObject $ParameterHashtable + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $ParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterJson")) + { + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterObject")) + { + $TemplateParameterObject.Remove("`$schema") + $TemplateParameterObject.Remove("contentVersion") + $NestedValues = $TemplateParameterObject.parameters + if ($null -ne $NestedValues) + { + $TemplateParameterObject.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $TemplateParameterObject[$_.Name] = $_.Value } + } + + $TemplateParameterJson = ConvertTo-Json -InputObject $TemplateParameterObject + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterObject") + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (New-Guid).Guid + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + if ($PSBoundParameters.ContainsKey("ResourceGroupName")) + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + else + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Resources` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overriden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Resources` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/how-to.md @@ -0,0 +1,60 @@ +# How-To +This document describes how to develop for `Az.Resources`. + +## Building `Az.Resources` +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.Resources` +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.Resources` +To pack `Az.Resources` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Resources`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Resources.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Resources.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Resources`. + - `-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.Resources` 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`. +- `generate-portal-ux.ps1` + - Generates a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +- `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/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/license.txt @@ -0,0 +1,203 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md @@ -0,0 +1,598 @@ +### AzADApplication [Get, New, Remove, Update] `IApplication, Boolean` + - TenantId `String` + - ObjectId `String` + - IncludeDeleted `SwitchParameter` + - InputObject `IResourcesIdentity` + - HardDelete `SwitchParameter` + - Filter `String` + - IdentifierUri `String` + - DisplayNameStartWith `String` + - DisplayName `String` + - ApplicationId `String` + - AllowGuestsSignIn `SwitchParameter` + - AllowPassthroughUser `SwitchParameter` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenants `SwitchParameter` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes` + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `SwitchParameter` + - Oauth2AllowUrlPathMatching `SwitchParameter` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `SwitchParameter` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `SwitchParameter` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + - Parameter `IApplicationCreateParameters` + - PassThru `SwitchParameter` + - AvailableToOtherTenant `SwitchParameter` + +### AzADApplicationOwner [Add, Get, Remove] `Boolean, IDirectoryObject` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADDeletedApplication [Restore] `IApplication` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + +### AzADGroup [Get, New, Remove] `IAdGroup, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayNameStartsWith `String` + - DisplayName `String` + - AdditionalProperties `Hashtable` + - MailNickname `String` + - Parameter `IGroupCreateParameters` + - PassThru `SwitchParameter` + +### AzADGroupMember [Add, Get, Remove, Test] `Boolean, IDirectoryObject, SwitchParameter` + - GroupObjectId `String` + - TenantId `String` + - MemberObjectId `String[]` + - MemberUserPrincipalName `String[]` + - GroupObject `IAdGroup` + - GroupDisplayName `String` + - InputObject `IResourcesIdentity` + - ObjectId `String` + - ShowOwner `SwitchParameter` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IGroupAddMemberParameters` + - DisplayName `String` + - GroupId `String` + - MemberId `String` + +### AzADGroupMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IGroupGetMemberGroupsParameters` + +### AzADGroupOwner [Add, Remove] `Boolean` + - ObjectId `String` + - TenantId `String` + - GroupObjectId `String` + - MemberObjectId `String[]` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADObject [Get] `IDirectoryObject` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - IncludeDirectoryObjectReference `SwitchParameter` + - ObjectId `String[]` + - Type `String[]` + - Parameter `IGetObjectsParameters` + +### AzADServicePrincipal [Get, New, Remove, Update] `IServicePrincipal, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ApplicationObject `IApplication` + - ServicePrincipalName `String` + - DisplayNameBeginsWith `String` + - DisplayName `String` + - ApplicationId `String` + - AccountEnabled `SwitchParameter` + - AppId `String` + - AppRoleAssignmentRequired `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + - Parameter `IServicePrincipalCreateParameters` + - PassThru `SwitchParameter` + +### AzADServicePrincipalOwner [Get] `IDirectoryObject` + - ObjectId `String` + - TenantId `String` + +### AzADUser [Get, New, Remove, Update] `IUser, Boolean` + - TenantId `String` + - UpnOrObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayName `String` + - StartsWith `String` + - Mail `String` + - MailNickname `String` + - Parameter `IUserCreateParameters` + - AccountEnabled `SwitchParameter` + - GivenName `String` + - ImmutableId `String` + - PasswordProfile `IPasswordProfile` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType` + - PassThru `SwitchParameter` + - EnableAccount `SwitchParameter` + +### AzADUserMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IUserGetMemberGroupsParameters` + +### AzApplicationKeyCredentials [Get, Update] `IKeyCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IKeyCredentialsUpdateParameters` + - Value `IKeyCredential[]` + +### AzApplicationPasswordCredentials [Get, Update] `IPasswordCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IPasswordCredentialsUpdateParameters` + - Value `IPasswordCredential[]` + +### AzAuthorizationOperation [Get] `IOperation` + +### AzClassicAdministrator [Get] `IClassicAdministrator` + - SubscriptionId `String[]` + +### AzDenyAssignment [Get] `IDenyAssignment` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - Filter `String` + +### AzDeployment [Get, New, Remove, Set, Stop, Test] `IDeploymentExtended, Boolean, IDeploymentValidateResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Top `Int32` + - Parameter `IDeployment` + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - PassThru `SwitchParameter` + +### AzDeploymentExistence [Test] `Boolean` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDeploymentOperation [Get] `IDeploymentOperation` + - DeploymentName `String` + - SubscriptionId `String[]` + - ResourceGroupName `String` + - OperationId `String` + - DeploymentObject `IDeploymentExtended` + - InputObject `IResourcesIdentity` + - Top `Int32` + +### AzDeploymentTemplate [Export] `IDeploymentExportResultTemplate` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDomain [Get] `IDomain` + - TenantId `String` + - Name `String` + - InputObject `IResourcesIdentity` + - Filter `String` + +### AzElevateGlobalAdministratorAccess [Invoke] `Boolean` + +### AzEntity [Get] `IEntityInfo` + - Filter `String` + - GroupName `String` + - Search `String` + - Select `String` + - Skip `Int32` + - Skiptoken `String` + - Top `Int32` + - View `String` + - CacheControl `String` + +### AzManagedApplication [Get, New, Remove, Set, Update] `IApplication, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplication` + - ApplicationDefinitionId `String` + - IdentityType `ResourceIdentityType` + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagedApplicationDefinition [Get, New, Remove, Set] `IApplicationDefinition, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplicationDefinition` + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - PackageFileUri `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagementGroup [Get, New, Remove, Set, Update] `IManagementGroup, IManagementGroupInfo, Boolean` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Expand `String` + - Filter `String` + - Recurse `SwitchParameter` + - CacheControl `String` + - DisplayName `String` + - Name `String` + - ParentId `String` + - CreateManagementGroupRequest `ICreateManagementGroupRequest` + - PatchGroupRequest `IPatchManagementGroupRequest` + +### AzManagementGroupDescendant [Get] `IDescendantInfo` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Top `Int32` + +### AzManagementGroupSubscription [New, Remove] `Boolean` + - GroupId `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - CacheControl `String` + +### AzManagementLock [Get, New, Remove, Set] `IManagementLockObject, Boolean` + - SubscriptionId `String[]` + - LockName `String` + - ResourceGroupName `String` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Level `LockLevel` + - Note `String` + - Owner `IManagementLockOwner[]` + - Parameter `IManagementLockObject` + +### AzNameAvailability [Test] `ICheckNameAvailabilityResult` + - Name `String` + - Type `Type` + - CheckNameAvailabilityRequest `ICheckNameAvailabilityRequest` + +### AzOAuth2PermissionGrant [Get, New, Remove] `IOAuth2PermissionGrant, Boolean` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ClientId `String` + - ConsentType `ConsentType` + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + - Body `IOAuth2PermissionGrant` + +### AzPermission [Get] `IPermission` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + +### AzPolicyAssignment [Get, New, Remove] `IPolicyAssignment` + - Id `String` + - Name `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - PolicyDefinitionId `String` + - IncludeDescendent `SwitchParameter` + - Filter `String` + - Parameter `IPolicyAssignment` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - SkuName `String` + - SkuTier `String` + - PropertiesScope `String` + +### AzPolicyDefinition [Get, New, Remove, Set] `IPolicyDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicyDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzPolicySetDefinition [Get, New, Remove, Set] `IPolicySetDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicySetDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzProviderFeature [Get, Register] `IFeatureResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + +### AzProviderOperationsMetadata [Get] `IProviderOperationsMetadata` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + +### AzResource [Get, Move, New, Remove, Set, Test, Update] `IGenericResource, Boolean` + - ResourceId `String` + - Name `String` + - ParentResourcePath `String` + - ProviderNamespace `String` + - ResourceGroupName `String` + - ResourceType `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - SourceResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - Expand `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Filter `String` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + - IdentityType `ResourceIdentityType` + - IdentityUserAssignedIdentity `Hashtable` + - Kind `String` + - Location `String` + - ManagedBy `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + +### AzResourceGroup [Export, Get, New, Remove, Set, Test, Update] `IResourceGroupExportResult, IResourceGroup, Boolean` + - ResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Id `String` + - Filter `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Option `String` + - Resource `String[]` + - Parameter `IExportTemplateRequest` + - Location `String` + - ManagedBy `String` + +### AzResourceLink [Get, New, Remove, Set] `IResourceLink, Boolean` + - ResourceId `String` + - InputObject `IResourcesIdentity` + - SubscriptionId `String[]` + - Scope `String` + - FilterById `String` + - FilterByScope `Filter` + - Note `String` + - TargetId `String` + - Parameter `IResourceLink` + +### AzResourceMove [Test] `Boolean` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + +### AzResourceProvider [Get, Register, Unregister] `IProvider` + - SubscriptionId `String[]` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + - Top `Int32` + +### AzResourceProviderOperationDetail [Get] `IResourceProviderOperationDefinition` + - ResourceProviderNamespace `String` + +### AzRoleAssignment [Get, New, Remove] `IRoleAssignment` + - Id `String` + - Name `String` + - Scope `String` + - RoleId `String` + - InputObject `IResourcesIdentity` + - ParentResourceId `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - ExpandPrincipalGroups `String` + - ServicePrincipalName `String` + - SignInName `String` + - Filter `String` + - CanDelegate `SwitchParameter` + - PrincipalId `String` + - RoleDefinitionId `String` + - Parameter `IRoleAssignmentCreateParameters` + - PrincipalType `PrincipalType` + +### AzRoleDefinition [Get, New, Remove, Set] `IRoleDefinition` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Custom `SwitchParameter` + - Filter `String` + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - RoleDefinition `IRoleDefinition` + +### AzSubscriptionLocation [Get] `ILocation` + - SubscriptionId `String[]` + +### AzTag [Get, New, Remove] `ITagDetails, Boolean` + - SubscriptionId `String[]` + - Name `String` + - Value `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + +### AzTenantBackfill [Start] `ITenantBackfillStatusResult` + +### AzTenantBackfillStatus [Invoke] `ITenantBackfillStatusResult` + diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/ModelSurface.md @@ -0,0 +1,1645 @@ +### AddOwnerParameters \ [Api16] + - Url `String` + +### AdGroup \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - Mail `String` + - MailEnabled `Boolean?` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - SecurityEnabled `Boolean?` + +### AliasPathType [Api20180501] + - ApiVersion `String[]` + - Path `String` + +### AliasType [Api20180501] + - Name `String` + - Path `IAliasPathType[]` + +### Appliance [Api20160901Preview] + - DefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceArtifact [Api20160901Preview] + - Name `String` + - Type `ApplianceArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplianceDefinition [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplianceDefinitionListResult [Api20160901Preview] + - NextLink `String` + - Value `IApplianceDefinition[]` + +### ApplianceDefinitionProperties [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - PackageFileUri `String` + +### ApplianceListResult [Api20160901Preview] + - NextLink `String` + - Value `IAppliance[]` + +### AppliancePatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceProperties [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### AppliancePropertiesPatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplianceProviderAuthorization [Api20160901Preview] + - PrincipalId `String` + - RoleDefinitionId `String` + +### Application \ [Api16, Api20170901, Api20180601] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppId `String` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DefinitionId `String` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - Id `String` + - IdentifierUri `String[]` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - Kind `String` + - KnownClientApplication `String[]` + - Location `String` + - LogoutUrl `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - ObjectId `String` + - ObjectType `String` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - PasswordCredentials `IPasswordCredential[]` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - ProvisioningState `String` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + - WwwHomepage `String` + +### ApplicationArtifact [Api20170901] + - Name `String` + - Type `ApplicationArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplicationBase [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationCreateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationDefinition [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplicationDefinitionListResult [Api20180601] + - NextLink `String` + - Value `IApplicationDefinition[]` + +### ApplicationDefinitionProperties [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IsEnabled `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - PackageFileUri `String` + +### ApplicationListResult [Api16, Api20180601] + - NextLink `String` + - OdataNextLink `String` + - Value `IApplication[]` + +### ApplicationPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplicationProperties [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationPropertiesPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationProviderAuthorization [Api20170901] + - PrincipalId `String` + - RoleDefinitionId `String` + +### ApplicationUpdateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### AppRole [Api16] + - AllowedMemberType `String[]` + - Description `String` + - DisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Value `String` + +### BasicDependency [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### CheckGroupMembershipParameters \ [Api16] + - GroupId `String` + - MemberId `String` + +### CheckGroupMembershipResult \ [Api16] + - Value `Boolean?` + +### CheckNameAvailabilityRequest [Api20180301Preview] + - Name `String` + - Type `Type?` **{ProvidersMicrosoftManagementGroups}** + +### CheckNameAvailabilityResult [Api20180301Preview] + - Message `String` + - NameAvailable `Boolean?` + - Reason `Reason?` **{AlreadyExists, Invalid}** + +### ClassicAdministrator [Api20150701] + - EmailAddress `String` + - Id `String` + - Name `String` + - Role `String` + - Type `String` + +### ClassicAdministratorListResult [Api20150701] + - NextLink `String` + - Value `IClassicAdministrator[]` + +### ClassicAdministratorProperties [Api20150701] + - EmailAddress `String` + - Role `String` + +### ComponentsSchemasIdentityPropertiesUserassignedidentitiesAdditionalproperties [Api20180501] + - ClientId `String` + - PrincipalId `String` + +### CreateManagementGroupChildInfo [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### CreateManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### CreateManagementGroupProperties [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### CreateManagementGroupRequest [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### CreateParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### DebugSetting [Api20180501] + - DetailLevel `String` + +### DenyAssignment [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - Id `String` + - IsSystemProtected `Boolean?` + - Name `String` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + - Type `String` + +### DenyAssignmentListResult [Api20180701Preview] + - NextLink `String` + - Value `IDenyAssignment[]` + +### DenyAssignmentPermission [Api20180701Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### DenyAssignmentProperties [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - IsSystemProtected `Boolean?` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + +### Dependency [Api20180501] + - DependsOn `IBasicDependency[]` + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### Deployment [Api20180501] + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentExportResult [Api20180501] + - Template `IDeploymentExportResultTemplate` + +### DeploymentExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Id `String` + - Location `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - Name `String` + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + - Type `String` + +### DeploymentListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentExtended[]` + +### DeploymentOperation [Api20180501] + - Id `String` + - OperationId `String` + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationProperties [Api20180501] + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationsListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentOperation[]` + +### DeploymentProperties [Api20180501] + - DebugSettingDetailLevel `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentPropertiesExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentValidateResult [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DescendantInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - ParentId `String` + - Type `String` + +### DescendantInfoProperties [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### DescendantListResult [Api20180301Preview] + - NextLink `String` + - Value `IDescendantInfo[]` + +### DescendantParentGroupInfo [Api20180301Preview] + - Id `String` + +### DirectoryObject \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - ObjectId `String` + - ObjectType `String` + +### DirectoryObjectListResult [Api16] + - OdataNextLink `String` + - Value `IDirectoryObject[]` + +### Domain \ [Api16] + - AuthenticationType `String` + - IsDefault `Boolean?` + - IsVerified `Boolean?` + - Name `String` + +### DomainListResult [Api16] + - Value `IDomain[]` + +### EntityInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - InheritedPermission `String` + - Name `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + - Type `String` + +### EntityInfoProperties [Api20180301Preview] + - DisplayName `String` + - InheritedPermission `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + +### EntityListResult [Api20180301Preview] + - Count `Int32?` + - NextLink `String` + - Value `IEntityInfo[]` + +### EntityParentGroupInfo [Api20180301Preview] + - Id `String` + +### ErrorDetails [Api20180301Preview] + - Code `String` + - Detail `String` + - Message `String` + +### ErrorMessage [Api16] + - Message `String` + +### ErrorResponse [Api20160901Preview, Api20180301Preview] + - ErrorCode `String` + - ErrorDetail `String` + - ErrorMessage `String` + - HttpStatus `String` + +### ExportTemplateRequest [Api20180501] + - Option `String` + - Resource `String[]` + +### FeatureOperationsListResult [Api20151201] + - NextLink `String` + - Value `IFeatureResult[]` + +### FeatureProperties [Api20151201] + - State `String` + +### FeatureResult [Api20151201] + - Id `String` + - Name `String` + - State `String` + - Type `String` + +### GenericResource [Api20160901Preview, Api20180501] + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IdentityUserAssignedIdentity `IIdentityUserAssignedIdentities ` + - Kind `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### GetObjectsParameters \ [Api16] + - IncludeDirectoryObjectReference `Boolean?` + - ObjectId `String[]` + - Type `String[]` + +### GraphError [Api16] + - ErrorMessageValueMessage `String` + - OdataErrorCode `String` + +### GroupAddMemberParameters \ [Api16] + - Url `String` + +### GroupCreateParameters \ [Api16] + - DisplayName `String` + - MailEnabled `Boolean` + - MailNickname `String` + - SecurityEnabled `Boolean` + +### GroupGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### GroupGetMemberGroupsResult [Api16] + - Value `String[]` + +### GroupListResult [Api16] + - OdataNextLink `String` + - Value `IAdGroup[]` + +### HttpMessage [Api20180501] + - Content `IHttpMessageContent` + +### Identity [Api20160901Preview, Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - UserAssignedIdentity `IIdentityUserAssignedIdentities ` + +### Identity1 [Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + +### InformationalUrl [Api16] + - Marketing `String` + - Privacy `String` + - Support `String` + - TermsOfService `String` + +### KeyCredential \ [Api16] + - CustomKeyIdentifier `String` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Type `String` + - Usage `String` + - Value `String` + +### KeyCredentialListResult [Api16] + - Value `IKeyCredential[]` + +### KeyCredentialsUpdateParameters [Api16] + - Value `IKeyCredential[]` + +### Location [Api20160601] + - DisplayName `String` + - Id `String` + - Latitude `String` + - Longitude `String` + - Name `String` + - SubscriptionId `String` + +### LocationListResult [Api20160601] + - Value `ILocation[]` + +### ManagementGroup [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### ManagementGroupChildInfo [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### ManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### ManagementGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - TenantId `String` + - Type `String` + +### ManagementGroupInfoProperties [Api20180301Preview] + - DisplayName `String` + - TenantId `String` + +### ManagementGroupListResult [Api20180301Preview] + - NextLink `String` + - Value `IManagementGroupInfo[]` + +### ManagementGroupProperties [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### ManagementLockListResult [Api20160901] + - NextLink `String` + - Value `IManagementLockObject[]` + +### ManagementLockObject [Api20160901] + - Id `String` + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Name `String` + - Note `String` + - Owner `IManagementLockOwner[]` + - Type `String` + +### ManagementLockOwner [Api20160901] + - ApplicationId `String` + +### ManagementLockProperties [Api20160901] + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Note `String` + - Owner `IManagementLockOwner[]` + +### OAuth2Permission [Api16] + - AdminConsentDescription `String` + - AdminConsentDisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Type `String` + - UserConsentDescription `String` + - UserConsentDisplayName `String` + - Value `String` + +### OAuth2PermissionGrant [Api16] + - ClientId `String` + - ConsentType `ConsentType?` **{AllPrincipals, Principal}** + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + +### OAuth2PermissionGrantListResult [Api16] + - OdataNextLink `String` + - Value `IOAuth2PermissionGrant[]` + +### OdataError [Api16] + - Code `String` + - ErrorMessageValueMessage `String` + +### OnErrorDeployment [Api20180501] + - DeploymentName `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### OnErrorDeploymentExtended [Api20180501] + - DeploymentName `String` + - ProvisioningState `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### Operation [Api20151201, Api20180301Preview] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayResource `String` + - Name `String` + +### OperationDisplay [Api20151201] + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationDisplayProperties [Api20180301Preview] + - Description `String` + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationListResult [Api20151201, Api20180301Preview] + - NextLink `String` + - Value `IOperation[]` + +### OperationResults [Api20180301Preview] + - Id `String` + - Name `String` + - ProvisioningState `String` + - Type `String` + +### OperationResultsProperties [Api20180301Preview] + - ProvisioningState `String` + +### OptionalClaim [Api16] + - AdditionalProperty `IOptionalClaimAdditionalProperties` + - Essential `Boolean?` + - Name `String` + - Source `String` + +### OptionalClaims [Api16] + - AccessToken `IOptionalClaim[]` + - IdToken `IOptionalClaim[]` + - SamlToken `IOptionalClaim[]` + +### ParametersLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### ParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### PasswordCredential \ [Api16] + - CustomKeyIdentifier `Byte[]` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Value `String` + +### PasswordCredentialListResult [Api16] + - Value `IPasswordCredential[]` + +### PasswordCredentialsUpdateParameters [Api16] + - Value `IPasswordCredential[]` + +### PasswordProfile \ [Api16] + - ForceChangePasswordNextLogin `Boolean?` + - Password `String` + +### PatchManagementGroupRequest [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### Permission [Api20150701, Api201801Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### PermissionGetResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IPermission[]` + +### Plan [Api20160901Preview, Api20180501] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PlanPatchable [Api20160901Preview] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PolicyAssignment [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - Name `String` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + - SkuName `String` + - SkuTier `String` + - Type `String` + +### PolicyAssignmentListResult [Api20151101, Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyAssignment[]` + +### PolicyAssignmentProperties [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + +### PolicyDefinition [Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Name `String` + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Property `IPolicyDefinitionProperties` + - Type `String` + +### PolicyDefinitionListResult [Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyDefinition[]` + +### PolicyDefinitionProperties [Api20161201] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicyDefinitionReference [Api20180501] + - Parameter `IPolicyDefinitionReferenceParameters` + - PolicyDefinitionId `String` + +### PolicySetDefinition [Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Name `String` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Type `String` + +### PolicySetDefinitionListResult [Api20180501] + - NextLink `String` + - Value `IPolicySetDefinition[]` + +### PolicySetDefinitionProperties [Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicySku [Api20180501] + - Name `String` + - Tier `String` + +### PreAuthorizedApplication [Api16] + - AppId `String` + - Extension `IPreAuthorizedApplicationExtension[]` + - Permission `IPreAuthorizedApplicationPermission[]` + +### PreAuthorizedApplicationExtension [Api16] + - Condition `String[]` + +### PreAuthorizedApplicationPermission [Api16] + - AccessGrant `String[]` + - DirectAccessGrant `Boolean?` + +### Principal [Api20180701Preview] + - Id `String` + - Type `String` + +### Provider [Api20180501] + - Id `String` + - Namespace `String` + - RegistrationState `String` + - ResourceType `IProviderResourceType[]` + +### ProviderListResult [Api20180501] + - NextLink `String` + - Value `IProvider[]` + +### ProviderOperation [Api20150701, Api201801Preview] + - Description `String` + - DisplayName `String` + - IsDataAction `Boolean?` + - Name `String` + - Origin `String` + - Property `IProviderOperationProperties` + +### ProviderOperationsMetadata [Api20150701, Api201801Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - Operation `IProviderOperation[]` + - ResourceType `IResourceType[]` + - Type `String` + +### ProviderOperationsMetadataListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IProviderOperationsMetadata[]` + +### ProviderResourceType [Api20180501] + - Alias `IAliasType[]` + - ApiVersion `String[]` + - Location `String[]` + - Property `IProviderResourceTypeProperties ` + - ResourceType `String` + +### RequiredResourceAccess \ [Api16] + - ResourceAccess `IResourceAccess[]` + - ResourceAppId `String` + +### Resource [Api20160901Preview] + - Id `String` + - Location `String` + - Name `String` + - Tag `IResourceTags ` + - Type `String` + +### ResourceAccess \ [Api16] + - Id `String` + - Type `String` + +### ResourceGroup [Api20180501] + - Id `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupTags ` + - Type `String` + +### ResourceGroupExportResult [Api20180501] + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Template `IResourceGroupExportResultTemplate` + +### ResourceGroupListResult [Api20180501] + - NextLink `String` + - Value `IResourceGroup[]` + +### ResourceGroupPatchable [Api20180501] + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupPatchableTags ` + +### ResourceGroupProperties [Api20180501] + - ProvisioningState `String` + +### ResourceLink [Api20160901] + - Id `String` + - Name `String` + - Note `String` + - SourceId `String` + - TargetId `String` + - Type `IResourceLinkType` + +### ResourceLinkProperties [Api20160901] + - Note `String` + - SourceId `String` + - TargetId `String` + +### ResourceLinkResult [Api20160901] + - NextLink `String` + - Value `IResourceLink[]` + +### ResourceListResult [Api20180501] + - NextLink `String` + - Value `IGenericResource[]` + +### ResourceManagementErrorWithDetails [Api20180501] + - Code `String` + - Detail `IResourceManagementErrorWithDetails[]` + - Message `String` + - Target `String` + +### ResourceProviderOperationDefinition [Api20151101] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayPublisher `String` + - DisplayResource `String` + - Name `String` + +### ResourceProviderOperationDetailListResult [Api20151101] + - NextLink `String` + - Value `IResourceProviderOperationDefinition[]` + +### ResourceProviderOperationDisplayProperties [Api20151101] + - Description `String` + - Operation `String` + - Provider `String` + - Publisher `String` + - Resource `String` + +### ResourcesIdentity [Models] + - ApplianceDefinitionId `String` + - ApplianceDefinitionName `String` + - ApplianceId `String` + - ApplianceName `String` + - ApplicationDefinitionId `String` + - ApplicationDefinitionName `String` + - ApplicationId `String` + - ApplicationId1 `String` + - ApplicationName `String` + - ApplicationObjectId `String` + - DenyAssignmentId `String` + - DeploymentName `String` + - DomainName `String` + - FeatureName `String` + - GroupId `String` + - GroupObjectId `String` + - Id `String` + - LinkId `String` + - LockName `String` + - ManagementGroupId `String` + - MemberObjectId `String` + - ObjectId `String` + - OperationId `String` + - OwnerObjectId `String` + - ParentResourcePath `String` + - PolicyAssignmentId `String` + - PolicyAssignmentName `String` + - PolicyDefinitionName `String` + - PolicySetDefinitionName `String` + - ResourceGroupName `String` + - ResourceId `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - RoleAssignmentId `String` + - RoleAssignmentName `String` + - RoleDefinitionId `String` + - RoleId `String` + - Scope `String` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - TagName `String` + - TagValue `String` + - TenantId `String` + - UpnOrObjectId `String` + +### ResourcesMoveInfo [Api20180501] + - Resource `String[]` + - TargetResourceGroup `String` + +### ResourceType [Api20150701, Api201801Preview] + - DisplayName `String` + - Name `String` + - Operation `IProviderOperation[]` + +### RoleAssignment [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - Id `String` + - Name `String` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + - Type `String` + +### RoleAssignmentCreateParameters [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentListResult [Api20150701, Api20180901Preview] + - NextLink `String` + - Value `IRoleAssignment[]` + +### RoleAssignmentProperties [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentPropertiesWithScope [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + +### RoleDefinition [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Id `String` + - Name `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - Type `String` + +### RoleDefinitionListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IRoleDefinition[]` + +### RoleDefinitionProperties [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + +### ServicePrincipal \ [Api16] + - AccountEnabled `Boolean?` + - AlternativeName `String[]` + - AppDisplayName `String` + - AppId `String` + - AppOwnerTenantId `String` + - AppRole `IAppRole[]` + - AppRoleAssignmentRequired `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - Homepage `String` + - KeyCredentials `IKeyCredential[]` + - LogoutUrl `String` + - Name `String[]` + - Oauth2Permission `IOAuth2Permission[]` + - ObjectId `String` + - ObjectType `String` + - PasswordCredentials `IPasswordCredential[]` + - PreferredTokenSigningKeyThumbprint `String` + - PublisherName `String` + - ReplyUrl `String[]` + - SamlMetadataUrl `String` + - Tag `String[]` + - Type `String` + +### ServicePrincipalBase [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalCreateParameters [Api16] + - AccountEnabled `Boolean?` + - AppId `String` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalListResult [Api16] + - OdataNextLink `String` + - Value `IServicePrincipal[]` + +### ServicePrincipalObjectResult [Api16] + - OdataMetadata `String` + - Value `String` + +### ServicePrincipalUpdateParameters [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### SignInName \ [Api16] + - Type `String` + - Value `String` + +### Sku [Api20160901Preview, Api20180501] + - Capacity `Int32?` + - Family `String` + - Model `String` + - Name `String` + - Size `String` + - Tier `String` + +### Subscription [Api20160601] + - AuthorizationSource `String` + - DisplayName `String` + - Id `String` + - PolicyLocationPlacementId `String` + - PolicyQuotaId `String` + - PolicySpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + - State `SubscriptionState?` **{Deleted, Disabled, Enabled, PastDue, Warned}** + - SubscriptionId `String` + +### SubscriptionPolicies [Api20160601] + - LocationPlacementId `String` + - QuotaId `String` + - SpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + +### TagCount [Api20180501] + - Type `String` + - Value `Int32?` + +### TagDetails [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagName `String` + - Value `ITagValue[]` + +### TagsListResult [Api20180501] + - NextLink `String` + - Value `ITagDetails[]` + +### TagValue [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagValue1 `String` + +### TargetResource [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### TemplateLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### TenantBackfillStatusResult [Api20180301Preview] + - Status `Status?` **{Cancelled, Completed, Failed, NotStarted, NotStartedButGroupsExist, Started}** + - TenantId `String` + +### TenantIdDescription [Api20160601] + - Id `String` + - TenantId `String` + +### TenantListResult [Api20160601] + - NextLink `String` + - Value `ITenantIdDescription[]` + +### User \ [Api16] + - AccountEnabled `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - PrincipalName `String` + - SignInName `ISignInName[]` + - Surname `String` + - Type `UserType?` **{Guest, Member}** + - UsageLocation `String` + +### UserBase \ [Api16] + - GivenName `String` + - ImmutableId `String` + - Surname `String` + - UsageLocation `String` + - UserType `UserType?` **{Guest, Member}** + +### UserCreateParameters \ [Api16] + - AccountEnabled `Boolean` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + +### UserGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### UserGetMemberGroupsResult [Api16] + - Value `String[]` + +### UserListResult [Api16] + - OdataNextLink `String` + - Value `IUser[]` + +### UserUpdateParameters \ [Api16] + - AccountEnabled `Boolean?` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/tools/Resources/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/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/AzureAI.Assets/target/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/.gitattributes b/tests-upgrade/tests-emitter/CodeSigning.Management/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.csproj b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.csproj new file mode 100644 index 00000000000..8be8b921a36 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.CodeSigning.private + false + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning + true + false + ./bin + $(OutputPath) + Az.CodeSigning.nuspec + true + + + 1998, 1591 + true + + + + false + TRACE;DEBUG;NETSTANDARD + + + + true + true + MSSharedLibKey.snk + TRACE;RELEASE;NETSTANDARD;SIGN + + + + + + + + + $(DefaultItemExcludes);resources/** + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.nuspec b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.nuspec new file mode 100644 index 00000000000..e9fe9548284 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.nuspec @@ -0,0 +1,32 @@ + + + + Az.CodeSigning + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: CodeSigning cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Sphere + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.psm1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.psm1 new file mode 100644 index 00000000000..d09e6f7316d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/Az.CodeSigning.psm1 @@ -0,0 +1,119 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.CodeSigning.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/CodeSigning.Management/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/CodeSigning.Management/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/README.md new file mode 100644 index 00000000000..cdc5585f5c8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/README.md @@ -0,0 +1,24 @@ + +# Az.CodeSigning +This directory contains the PowerShell module for the CodeSigning service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.CodeSigning`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/build-module.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/build-module.ps1 new file mode 100644 index 00000000000..954206398cc --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $NotIsolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +$isAzure = [System.Convert]::ToBoolean('true') + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.CodeSigning.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.CodeSigning.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.CodeSigning.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.CodeSigning' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: CodeSigning cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.CodeSigning.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and ((-not (Test-Path -Path $resourceModule)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..bc53547d3a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if (''.length -gt 0) { + $ModuleName = '' + } else { + $ModuleName = 'Az.CodeSigning' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('CodeSigning')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'CodeSigning' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/Az.CodeSigning.custom.psm1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/Az.CodeSigning.custom.psm1 new file mode 100644 index 00000000000..da48bfeafdf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/Az.CodeSigning.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.CodeSigning.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/README.md new file mode 100644 index 00000000000..2cbc19af758 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.CodeSigning` 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.CodeSigning.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.CodeSigning` 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.CodeSigning.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.CodeSigning.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.CodeSigning`. 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.CodeSigning.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.CodeSigning`. +- `Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.CodeSigning`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/docs/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/docs/README.md new file mode 100644 index 00000000000..6ff5309ec33 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.CodeSigning` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.CodeSigning` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/examples/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/export-surface.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/export-surface.ps1 new file mode 100644 index 00000000000..76c4d70b2c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.CodeSigning.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.CodeSigning' +$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/tests-upgrade/tests-emitter/CodeSigning.Management/target/exports/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/exports/README.md new file mode 100644 index 00000000000..74ad4000224 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.CodeSigning`. No other cmdlets in this repository are directly exported. What that means is the `Az.CodeSigning` module will run [Export-ModuleMember](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.CodeSigning.private.dll`) and from the `..\custom\Az.CodeSigning.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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-help.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-help.ps1 new file mode 100644 index 00000000000..f4cb7fda124 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CodeSigning.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.CodeSigning.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..bb3f436a4b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generate-portal-ux.ps1 @@ -0,0 +1,383 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.CodeSigning' +$rootModuleName = '' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + if ($Null -eq $example) + { + $example = @() + } + + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + if ($Null -eq $signature) + { + $signature = @() + } + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/Module.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/Module.cs new file mode 100644 index 00000000000..f3bb0bb7660 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/Module.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + public bool _useProxy = false; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.CodeSigning"; + + /// 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.CodeSigning"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_useProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/CodeSigningManagementClient.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/CodeSigningManagementClient.cs new file mode 100644 index 00000000000..d9b24832ffd --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/CodeSigningManagementClient.cs @@ -0,0 +1,5045 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Low-level API implementation for the CodeSigningManagementClient service. + /// Code Signing resource provider api. + /// + public partial class CodeSigningManagementClient + { + + /// update a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Parameters to create the certificate profile + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesCreate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a certificate profile. + /// + /// Parameters to create the certificate profile + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a certificate profile. + /// + /// Parameters to create the certificate profile + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Json string supplied to the CertificateProfilesCreate operation + /// 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.CodeSigning.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 CertificateProfilesCreateViaJsonString(string subscriptionId, string resourceGroupName, string accountName, string profileName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Json string supplied to the CertificateProfilesCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string accountName, string profileName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesCreateWithResult_Call (request, eventListener,sender); + } + } + + /// update a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Parameters to create the certificate profile + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesCreateWithResult(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesCreate_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Parameters to create the certificate profile + /// 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 CertificateProfilesCreate_Validate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(profileName),profileName); + await eventListener.AssertRegEx(nameof(profileName), profileName, @"^(?=.{5,100}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CertificateProfilesDelete(string subscriptionId, string resourceGroupName, string accountName, string profileName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a certificate profile. + /// + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CertificateProfilesDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CertificateProfilesDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile 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 CertificateProfilesDelete_Validate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(profileName),profileName); + await eventListener.AssertRegEx(nameof(profileName), profileName, @"^(?=.{5,100}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + } + } + + /// Get details of a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile 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.CodeSigning.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 CertificateProfilesGet(string subscriptionId, string resourceGroupName, string accountName, string profileName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get details of a certificate profile. + /// + /// 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.CodeSigning.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 CertificateProfilesGetViaIdentity(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get details of a certificate profile. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get details of a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesGetWithResult(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesGet_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile 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 CertificateProfilesGet_Validate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(profileName),profileName); + await eventListener.AssertRegEx(nameof(profileName), profileName, @"^(?=.{5,100}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + } + } + + /// List certificate profiles under a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account 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.CodeSigning.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 CertificateProfilesListByCodeSigningAccount(string subscriptionId, string resourceGroupName, string accountName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesListByCodeSigningAccount_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List certificate profiles under a trusted signing account. + /// + /// 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.CodeSigning.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 CertificateProfilesListByCodeSigningAccountViaIdentity(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesListByCodeSigningAccount_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List certificate profiles under a trusted signing account. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesListByCodeSigningAccountViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesListByCodeSigningAccountWithResult_Call (request, eventListener,sender); + } + } + + /// List certificate profiles under a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesListByCodeSigningAccountWithResult(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CertificateProfilesListByCodeSigningAccountWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesListByCodeSigningAccountWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CertificateProfilesListByCodeSigningAccount_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account 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 CertificateProfilesListByCodeSigningAccount_Validate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + } + } + + /// Revoke a certificate under a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Parameters to revoke the certificate profile + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesRevokeCertificate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate body, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "/revokeCertificate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesRevokeCertificate_Call (request, onNoContent,onDefault,eventListener,sender); + } + } + + /// Revoke a certificate under a certificate profile. + /// + /// Parameters to revoke the certificate profile + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CertificateProfilesRevokeCertificateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate body, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)/certificateProfiles/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + var profileName = _match.Groups["profileName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "/certificateProfiles/" + + profileName + + "/revokeCertificate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesRevokeCertificate_Call (request, onNoContent,onDefault,eventListener,sender); + } + } + + /// Revoke a certificate under a certificate profile. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Json string supplied to the CertificateProfilesRevokeCertificate operation + /// 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.CodeSigning.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 CertificateProfilesRevokeCertificateViaJsonString(string subscriptionId, string resourceGroupName, string accountName, string profileName, global::System.String jsonString, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "/certificateProfiles/" + + global::System.Uri.EscapeDataString(profileName) + + "/revokeCertificate" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CertificateProfilesRevokeCertificate_Call (request, onNoContent,onDefault,eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// 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.CodeSigning.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 CertificateProfilesRevokeCertificate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.NoContent: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Certificate profile name. + /// Parameters to revoke the certificate profile + /// 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 CertificateProfilesRevokeCertificate_Validate(string subscriptionId, string resourceGroupName, string accountName, string profileName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(profileName),profileName); + await eventListener.AssertRegEx(nameof(profileName), profileName, @"^(?=.{5,100}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The CheckAvailability request + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCheckNameAvailability(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCheckNameAvailability_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// The CheckAvailability request + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCheckNameAvailabilityViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCheckNameAvailability_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// The CheckAvailability request + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCheckNameAvailabilityViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCheckNameAvailabilityWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// The ID of the target subscription. The value must be an UUID. + /// Json string supplied to the CodeSigningAccountsCheckNameAvailability operation + /// 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.CodeSigning.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 CodeSigningAccountsCheckNameAvailabilityViaJsonString(string subscriptionId, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCheckNameAvailability_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// The ID of the target subscription. The value must be an UUID. + /// Json string supplied to the CodeSigningAccountsCheckNameAvailability operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCheckNameAvailabilityViaJsonStringWithResult(string subscriptionId, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCheckNameAvailabilityWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// The ID of the target subscription. The value must be an UUID. + /// The CheckAvailability request + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCheckNameAvailabilityWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/checkNameAvailability" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Post, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCheckNameAvailabilityWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCheckNameAvailabilityWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CheckNameAvailabilityResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCheckNameAvailability_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CheckNameAvailabilityResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The CheckAvailability request + /// an instance that will receive events. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task CodeSigningAccountsCheckNameAvailability_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// create a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters to create the trusted signing account + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCreate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a trusted Signing Account. + /// + /// Parameters to create the trusted signing account + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCreateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a trusted Signing Account. + /// + /// Parameters to create the trusted signing account + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCreateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Json string supplied to the CodeSigningAccountsCreate operation + /// 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.CodeSigning.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 CodeSigningAccountsCreateViaJsonString(string subscriptionId, string resourceGroupName, string accountName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsCreate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// create a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Json string supplied to the CodeSigningAccountsCreate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCreateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string accountName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// create a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters to create the trusted signing account + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsCreateWithResult(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsCreateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCreateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsCreate_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters to create the trusted signing account + /// 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 CodeSigningAccountsCreate_Validate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CodeSigningAccountsDelete(string subscriptionId, string resourceGroupName, string accountName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a trusted signing account. + /// + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CodeSigningAccountsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.CodeSigning.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 CodeSigningAccountsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account 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 CodeSigningAccountsDelete_Validate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + } + } + + /// Get a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account 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.CodeSigning.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 CodeSigningAccountsGet(string subscriptionId, string resourceGroupName, string accountName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a trusted Signing Account. + /// + /// 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.CodeSigning.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 CodeSigningAccountsGetViaIdentity(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a trusted Signing Account. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a trusted Signing Account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsGetWithResult(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsGet_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account 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 CodeSigningAccountsGet_Validate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + } + } + + /// Lists trusted signing accounts within a resource group. + /// The ID of the target subscription. The value must be an UUID. + /// 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.CodeSigning.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 CodeSigningAccountsListByResourceGroup(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists trusted signing accounts 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.CodeSigning.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 CodeSigningAccountsListByResourceGroupViaIdentity(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts$", 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.CodeSigning/codeSigningAccounts'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists trusted signing accounts within a resource group. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts$", 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.CodeSigning/codeSigningAccounts'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// Lists trusted signing accounts within a resource group. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListByResourceGroup_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// 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 CodeSigningAccountsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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\._\(\)]+$"); + } + } + + /// Lists trusted signing accounts within a subscription. + /// The ID of the target subscription. The value must be an UUID. + /// 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.CodeSigning.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 CodeSigningAccountsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists trusted signing accounts 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.CodeSigning.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 CodeSigningAccountsListBySubscriptionViaIdentity(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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/codeSigningAccounts'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Lists trusted signing accounts within a subscription. + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/codeSigningAccounts'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// Lists trusted signing accounts within a subscription. + /// The ID of the target subscription. The value must be an UUID. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsListBySubscription_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// 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 CodeSigningAccountsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// update a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters supplied to update the trusted signing account + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsUpdate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a trusted signing account. + /// + /// Parameters supplied to update the trusted signing account + /// 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.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a trusted signing account. + /// + /// Parameters supplied to update the trusted signing account + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-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.CodeSigning/codeSigningAccounts/(?[^/]+)$", 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.CodeSigning/codeSigningAccounts/{accountName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var accountName = _match.Groups["accountName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + accountName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Json string supplied to the CodeSigningAccountsUpdate operation + /// 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.CodeSigning.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 CodeSigningAccountsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string accountName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.CodeSigningAccountsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Json string supplied to the CodeSigningAccountsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string accountName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a trusted signing account. + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters supplied to update the trusted signing account + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task CodeSigningAccountsUpdateWithResult(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Microsoft.CodeSigning/codeSigningAccounts/" + + global::System.Uri.EscapeDataString(accountName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.CodeSigningAccountsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 CodeSigningAccountsUpdate_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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.CodeSigning.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Trusted Signing account name. + /// Parameters supplied to update the trusted signing account + /// 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 CodeSigningAccountsUpdate_Validate(string subscriptionId, string resourceGroupName, string accountName, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch body, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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(accountName),accountName); + await eventListener.AssertRegEx(nameof(accountName), accountName, @"^(?=.{3,24}$)[^0-9][A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// List the operations for the 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.CodeSigning.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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.CodeSigning/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the 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.CodeSigning.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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.CodeSigning/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.CodeSigning/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the provider + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-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.CodeSigning/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.CodeSigning/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.CodeSigning/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// List the operations for the provider + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListWithResult(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-02-05-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Microsoft.CodeSigning/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.PowerShell.cs new file mode 100644 index 00000000000..74fea73db2d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.PowerShell.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// SKU of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(AccountSkuTypeConverter))] + public partial class AccountSku + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal AccountSku(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)this).Name, 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 AccountSku(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)this).Name, 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.CodeSigning.Models.IAccountSku DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new AccountSku(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.CodeSigning.Models.IAccountSku DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new AccountSku(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.CodeSigning.Models.IAccountSku FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// SKU of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(AccountSkuTypeConverter))] + public partial interface IAccountSku + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.TypeConverter.cs new file mode 100644 index 00000000000..9d9c914e27c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AccountSkuTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AccountSku.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return AccountSku.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return AccountSku.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.cs new file mode 100644 index 00000000000..f9c5216f4c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// SKU of the trusted signing account. + public partial class AccountSku : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal + { + + /// Backing field for property. + private string _name; + + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public AccountSku() + { + + } + } + /// SKU of the trusted signing account. + public partial interface IAccountSku : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string Name { get; set; } + + } + /// SKU of the trusted signing account. + internal partial interface IAccountSkuInternal + + { + /// Name of the SKU. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.json.cs new file mode 100644 index 00000000000..2766462056c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/AccountSku.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// SKU of the trusted signing account. + public partial class AccountSku + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal AccountSku(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new AccountSku(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..5a35a25042b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.PowerShell.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial class Any + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Any(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Any(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Any(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Any(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial interface IAny + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..65053f3487a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Any.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Any.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..734918bd54a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..f781c179aa4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Any.json.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Anything + public partial class Any + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Any(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.PowerShell.cs new file mode 100644 index 00000000000..9127ccaf29a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.PowerShell.cs @@ -0,0 +1,258 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Properties of the certificate. + [System.ComponentModel.TypeConverter(typeof(CertificateTypeConverter))] + public partial class Certificate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Certificate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Revocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Revocation = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation) content.GetValueForProperty("Revocation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Revocation, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.RevocationTypeConverter.ConvertFrom); + } + if (content.Contains("SerialNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SerialNumber = (string) content.GetValueForProperty("SerialNumber",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SerialNumber, global::System.Convert.ToString); + } + if (content.Contains("SubjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SubjectName = (string) content.GetValueForProperty("SubjectName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SubjectName, global::System.Convert.ToString); + } + if (content.Contains("Thumbprint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Thumbprint = (string) content.GetValueForProperty("Thumbprint",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Thumbprint, global::System.Convert.ToString); + } + if (content.Contains("CreatedDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).CreatedDate = (string) content.GetValueForProperty("CreatedDate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).CreatedDate, global::System.Convert.ToString); + } + if (content.Contains("ExpiryDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).ExpiryDate = (string) content.GetValueForProperty("ExpiryDate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).ExpiryDate, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("RevocationRemark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRemark = (string) content.GetValueForProperty("RevocationRemark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRemark, global::System.Convert.ToString); + } + if (content.Contains("RevocationStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationStatus = (string) content.GetValueForProperty("RevocationStatus",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationStatus, global::System.Convert.ToString); + } + if (content.Contains("RevocationRequestedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRequestedAt = (global::System.DateTime?) content.GetValueForProperty("RevocationRequestedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRequestedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RevocationEffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationEffectiveAt = (global::System.DateTime?) content.GetValueForProperty("RevocationEffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationEffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RevocationReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationReason = (string) content.GetValueForProperty("RevocationReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationReason, global::System.Convert.ToString); + } + if (content.Contains("RevocationFailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationFailureReason = (string) content.GetValueForProperty("RevocationFailureReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationFailureReason, 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 Certificate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Revocation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Revocation = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation) content.GetValueForProperty("Revocation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Revocation, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.RevocationTypeConverter.ConvertFrom); + } + if (content.Contains("SerialNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SerialNumber = (string) content.GetValueForProperty("SerialNumber",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SerialNumber, global::System.Convert.ToString); + } + if (content.Contains("SubjectName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SubjectName = (string) content.GetValueForProperty("SubjectName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).SubjectName, global::System.Convert.ToString); + } + if (content.Contains("Thumbprint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Thumbprint = (string) content.GetValueForProperty("Thumbprint",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Thumbprint, global::System.Convert.ToString); + } + if (content.Contains("CreatedDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).CreatedDate = (string) content.GetValueForProperty("CreatedDate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).CreatedDate, global::System.Convert.ToString); + } + if (content.Contains("ExpiryDate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).ExpiryDate = (string) content.GetValueForProperty("ExpiryDate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).ExpiryDate, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("RevocationRemark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRemark = (string) content.GetValueForProperty("RevocationRemark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRemark, global::System.Convert.ToString); + } + if (content.Contains("RevocationStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationStatus = (string) content.GetValueForProperty("RevocationStatus",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationStatus, global::System.Convert.ToString); + } + if (content.Contains("RevocationRequestedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRequestedAt = (global::System.DateTime?) content.GetValueForProperty("RevocationRequestedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationRequestedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RevocationEffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationEffectiveAt = (global::System.DateTime?) content.GetValueForProperty("RevocationEffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationEffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("RevocationReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationReason = (string) content.GetValueForProperty("RevocationReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationReason, global::System.Convert.ToString); + } + if (content.Contains("RevocationFailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationFailureReason = (string) content.GetValueForProperty("RevocationFailureReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal)this).RevocationFailureReason, 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.CodeSigning.Models.ICertificate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Certificate(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.CodeSigning.Models.ICertificate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Certificate(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.CodeSigning.Models.ICertificate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties of the certificate. + [System.ComponentModel.TypeConverter(typeof(CertificateTypeConverter))] + public partial interface ICertificate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.TypeConverter.cs new file mode 100644 index 00000000000..61040ddba8f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CertificateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Certificate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Certificate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Certificate.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.cs new file mode 100644 index 00000000000..cf64f489a09 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the certificate. + public partial class Certificate : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal + { + + /// Backing field for property. + private string _createdDate; + + /// Certificate created date. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string CreatedDate { get => this._createdDate; set => this._createdDate = value; } + + /// Backing field for property. + private string _expiryDate; + + /// Certificate expiry date. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ExpiryDate { get => this._expiryDate; set => this._expiryDate = value; } + + /// Internal Acessors for Revocation + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateInternal.Revocation { get => (this._revocation = this._revocation ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Revocation()); set { {_revocation = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation _revocation; + + /// Revocations history of a certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation Revocation { get => (this._revocation = this._revocation ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Revocation()); set => this._revocation = value; } + + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public global::System.DateTime? RevocationEffectiveAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).EffectiveAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).EffectiveAt = value ?? default(global::System.DateTime); } + + /// Reason for the revocation failure. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string RevocationFailureReason { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).FailureReason; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).FailureReason = value ?? null; } + + /// Reason for revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string RevocationReason { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Reason; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Reason = value ?? null; } + + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string RevocationRemark { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Remark; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Remark = value ?? null; } + + /// The timestamp when the revocation is requested. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public global::System.DateTime? RevocationRequestedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).RequestedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).RequestedAt = value ?? default(global::System.DateTime); } + + /// Status of the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string RevocationStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)Revocation).Status = value ?? null; } + + /// Backing field for property. + private string _serialNumber; + + /// Serial number of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string SerialNumber { get => this._serialNumber; set => this._serialNumber = value; } + + /// Backing field for property. + private string _status; + + /// Status of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// Backing field for property. + private string _subjectName; + + /// Subject name of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string SubjectName { get => this._subjectName; set => this._subjectName = value; } + + /// Backing field for property. + private string _thumbprint; + + /// Thumbprint of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Thumbprint { get => this._thumbprint; set => this._thumbprint = value; } + + /// Creates an new instance. + public Certificate() + { + + } + } + /// Properties of the certificate. + public partial interface ICertificate : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Certificate created date. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Certificate created date.", + SerializedName = @"createdDate", + PossibleTypes = new [] { typeof(string) })] + string CreatedDate { get; set; } + /// Certificate expiry date. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Certificate expiry date.", + SerializedName = @"expiryDate", + PossibleTypes = new [] { typeof(string) })] + string ExpiryDate { get; set; } + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? RevocationEffectiveAt { get; set; } + /// Reason for the revocation failure. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Reason for the revocation failure.", + SerializedName = @"failureReason", + PossibleTypes = new [] { typeof(string) })] + string RevocationFailureReason { get; set; } + /// Reason for revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Reason for revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + string RevocationReason { get; set; } + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + string RevocationRemark { get; set; } + /// The timestamp when the revocation is requested. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp when the revocation is requested.", + SerializedName = @"requestedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? RevocationRequestedAt { get; set; } + /// Status of the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Status of the revocation.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "InProgress", "Failed")] + string RevocationStatus { get; set; } + /// Serial number of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Serial number of the certificate.", + SerializedName = @"serialNumber", + PossibleTypes = new [] { typeof(string) })] + string SerialNumber { get; set; } + /// Status of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Status of the certificate.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Expired", "Revoked")] + string Status { get; set; } + /// Subject name of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Subject name of the certificate.", + SerializedName = @"subjectName", + PossibleTypes = new [] { typeof(string) })] + string SubjectName { get; set; } + /// Thumbprint of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Thumbprint of the certificate.", + SerializedName = @"thumbprint", + PossibleTypes = new [] { typeof(string) })] + string Thumbprint { get; set; } + + } + /// Properties of the certificate. + internal partial interface ICertificateInternal + + { + /// Certificate created date. + string CreatedDate { get; set; } + /// Certificate expiry date. + string ExpiryDate { get; set; } + /// Revocations history of a certificate. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation Revocation { get; set; } + /// The timestamp when the revocation is effective. + global::System.DateTime? RevocationEffectiveAt { get; set; } + /// Reason for the revocation failure. + string RevocationFailureReason { get; set; } + /// Reason for revocation. + string RevocationReason { get; set; } + /// Remarks for the revocation. + string RevocationRemark { get; set; } + /// The timestamp when the revocation is requested. + global::System.DateTime? RevocationRequestedAt { get; set; } + /// Status of the revocation. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "InProgress", "Failed")] + string RevocationStatus { get; set; } + /// Serial number of the certificate. + string SerialNumber { get; set; } + /// Status of the certificate. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Expired", "Revoked")] + string Status { get; set; } + /// Subject name of the certificate. + string SubjectName { get; set; } + /// Thumbprint of the certificate. + string Thumbprint { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.json.cs new file mode 100644 index 00000000000..38ba4c28cce --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Certificate.json.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the certificate. + public partial class Certificate + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal Certificate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_revocation = If( json?.PropertyT("revocation"), out var __jsonRevocation) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Revocation.FromJson(__jsonRevocation) : _revocation;} + {_serialNumber = If( json?.PropertyT("serialNumber"), out var __jsonSerialNumber) ? (string)__jsonSerialNumber : (string)_serialNumber;} + {_subjectName = If( json?.PropertyT("subjectName"), out var __jsonSubjectName) ? (string)__jsonSubjectName : (string)_subjectName;} + {_thumbprint = If( json?.PropertyT("thumbprint"), out var __jsonThumbprint) ? (string)__jsonThumbprint : (string)_thumbprint;} + {_createdDate = If( json?.PropertyT("createdDate"), out var __jsonCreatedDate) ? (string)__jsonCreatedDate : (string)_createdDate;} + {_expiryDate = If( json?.PropertyT("expiryDate"), out var __jsonExpiryDate) ? (string)__jsonExpiryDate : (string)_expiryDate;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Certificate(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._revocation ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._revocation.ToJson(null,serializationMode) : null, "revocation" ,container.Add ); + AddIf( null != (((object)this._serialNumber)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._serialNumber.ToString()) : null, "serialNumber" ,container.Add ); + AddIf( null != (((object)this._subjectName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._subjectName.ToString()) : null, "subjectName" ,container.Add ); + AddIf( null != (((object)this._thumbprint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._thumbprint.ToString()) : null, "thumbprint" ,container.Add ); + AddIf( null != (((object)this._createdDate)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._createdDate.ToString()) : null, "createdDate" ,container.Add ); + AddIf( null != (((object)this._expiryDate)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._expiryDate.ToString()) : null, "expiryDate" ,container.Add ); + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.PowerShell.cs new file mode 100644 index 00000000000..43fcb889978 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Certificate profile resource. + [System.ComponentModel.TypeConverter(typeof(CertificateProfileTypeConverter))] + public partial class CertificateProfile + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CertificateProfile(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfilePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProfileType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProfileType = (string) content.GetValueForProperty("ProfileType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProfileType, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Certificate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Certificate = (System.Collections.Generic.List) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Certificate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateTypeConverter.ConvertFrom)); + } + if (content.Contains("CommonName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).CommonName = (string) content.GetValueForProperty("CommonName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).CommonName, global::System.Convert.ToString); + } + if (content.Contains("Organization")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Organization = (string) content.GetValueForProperty("Organization",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Organization, global::System.Convert.ToString); + } + if (content.Contains("OrganizationUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).OrganizationUnit = (string) content.GetValueForProperty("OrganizationUnit",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).OrganizationUnit, global::System.Convert.ToString); + } + if (content.Contains("StreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).StreetAddress = (string) content.GetValueForProperty("StreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).StreetAddress, global::System.Convert.ToString); + } + if (content.Contains("IncludeStreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeStreetAddress = (bool?) content.GetValueForProperty("IncludeStreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeStreetAddress, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("City")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).City = (string) content.GetValueForProperty("City",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).City, global::System.Convert.ToString); + } + if (content.Contains("IncludeCity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCity = (bool?) content.GetValueForProperty("IncludeCity",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCity, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("IncludeState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeState = (bool?) content.GetValueForProperty("IncludeState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeState, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("IncludeCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCountry = (bool?) content.GetValueForProperty("IncludeCountry",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCountry, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("PostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).PostalCode = (string) content.GetValueForProperty("PostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).PostalCode, global::System.Convert.ToString); + } + if (content.Contains("IncludePostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludePostalCode = (bool?) content.GetValueForProperty("IncludePostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludePostalCode, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnhancedKeyUsage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).EnhancedKeyUsage = (string) content.GetValueForProperty("EnhancedKeyUsage",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).EnhancedKeyUsage, global::System.Convert.ToString); + } + if (content.Contains("IdentityValidationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IdentityValidationId = (string) content.GetValueForProperty("IdentityValidationId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IdentityValidationId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Status, 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 CertificateProfile(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfilePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("ProfileType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProfileType = (string) content.GetValueForProperty("ProfileType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProfileType, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Certificate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Certificate = (System.Collections.Generic.List) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Certificate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateTypeConverter.ConvertFrom)); + } + if (content.Contains("CommonName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).CommonName = (string) content.GetValueForProperty("CommonName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).CommonName, global::System.Convert.ToString); + } + if (content.Contains("Organization")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Organization = (string) content.GetValueForProperty("Organization",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Organization, global::System.Convert.ToString); + } + if (content.Contains("OrganizationUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).OrganizationUnit = (string) content.GetValueForProperty("OrganizationUnit",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).OrganizationUnit, global::System.Convert.ToString); + } + if (content.Contains("StreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).StreetAddress = (string) content.GetValueForProperty("StreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).StreetAddress, global::System.Convert.ToString); + } + if (content.Contains("IncludeStreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeStreetAddress = (bool?) content.GetValueForProperty("IncludeStreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeStreetAddress, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("City")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).City = (string) content.GetValueForProperty("City",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).City, global::System.Convert.ToString); + } + if (content.Contains("IncludeCity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCity = (bool?) content.GetValueForProperty("IncludeCity",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCity, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("IncludeState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeState = (bool?) content.GetValueForProperty("IncludeState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeState, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("IncludeCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCountry = (bool?) content.GetValueForProperty("IncludeCountry",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludeCountry, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("PostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).PostalCode = (string) content.GetValueForProperty("PostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).PostalCode, global::System.Convert.ToString); + } + if (content.Contains("IncludePostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludePostalCode = (bool?) content.GetValueForProperty("IncludePostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IncludePostalCode, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnhancedKeyUsage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).EnhancedKeyUsage = (string) content.GetValueForProperty("EnhancedKeyUsage",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).EnhancedKeyUsage, global::System.Convert.ToString); + } + if (content.Contains("IdentityValidationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IdentityValidationId = (string) content.GetValueForProperty("IdentityValidationId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).IdentityValidationId, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).Status, 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.CodeSigning.Models.ICertificateProfile DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CertificateProfile(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.CodeSigning.Models.ICertificateProfile DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CertificateProfile(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.CodeSigning.Models.ICertificateProfile FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Certificate profile resource. + [System.ComponentModel.TypeConverter(typeof(CertificateProfileTypeConverter))] + public partial interface ICertificateProfile + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.TypeConverter.cs new file mode 100644 index 00000000000..2519ac1e865 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CertificateProfileTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CertificateProfile.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CertificateProfile.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CertificateProfile.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.cs new file mode 100644 index 00000000000..69768152702 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Certificate profile resource. + public partial class CertificateProfile : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IValidates, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ProxyResource(); + + /// Backing field for property. + private string _azureAsyncOperation; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string AzureAsyncOperation { get => this._azureAsyncOperation; set => this._azureAsyncOperation = value; } + + /// List of renewed certificates. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Certificate { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Certificate; } + + /// Used as L in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string City { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).City; } + + /// Used as CN in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string CommonName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).CommonName; } + + /// Used as C in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Country { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Country; } + + /// Enhanced key usage of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string EnhancedKeyUsage { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).EnhancedKeyUsage; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Id; } + + /// Identity validation id used for the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string IdentityValidationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IdentityValidationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IdentityValidationId = value ?? null; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public bool? IncludeCity { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeCity; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeCity = value ?? default(bool); } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public bool? IncludeCountry { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeCountry; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeCountry = value ?? default(bool); } + + /// Whether to include PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public bool? IncludePostalCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludePostalCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludePostalCode = value ?? default(bool); } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public bool? IncludeState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeState = value ?? default(bool); } + + /// Whether to include STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public bool? IncludeStreetAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeStreetAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).IncludeStreetAddress = value ?? default(bool); } + + /// Internal Acessors for Certificate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.Certificate { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Certificate; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Certificate = value; } + + /// Internal Acessors for City + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.City { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).City; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).City = value; } + + /// Internal Acessors for CommonName + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.CommonName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).CommonName; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).CommonName = value; } + + /// Internal Acessors for Country + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.Country { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Country; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Country = value; } + + /// Internal Acessors for EnhancedKeyUsage + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.EnhancedKeyUsage { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).EnhancedKeyUsage; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).EnhancedKeyUsage = value; } + + /// Internal Acessors for Organization + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.Organization { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Organization; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Organization = value; } + + /// Internal Acessors for OrganizationUnit + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.OrganizationUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).OrganizationUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).OrganizationUnit = value; } + + /// Internal Acessors for PostalCode + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.PostalCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).PostalCode; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).PostalCode = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.State { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).State; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).State = value; } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Status; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Status = value; } + + /// Internal Acessors for StreetAddress + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal.StreetAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).StreetAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).StreetAddress = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Name; } + + /// Used as O in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Organization { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Organization; } + + /// Used as OU in the private trust certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string OrganizationUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).OrganizationUnit; } + + /// Used as PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string PostalCode { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).PostalCode; } + + /// Profile type of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string ProfileType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).ProfileType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).ProfileType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileProperties()); set => this._property = value; } + + /// Status of the current operation on certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// Used as S in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string State { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).State; } + + /// Status of the certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Status { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).Status; } + + /// Used as STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string StreetAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)Property).StreetAddress; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).SystemDataLastModifiedByType = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__proxyResource).Type; } + + /// Creates an new instance. + public CertificateProfile() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Azure-AsyncOperation", out var __azureAsyncOperationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).AzureAsyncOperation = System.Linq.Enumerable.FirstOrDefault(__azureAsyncOperationHeader0) is string __headerAzureAsyncOperationHeader0 ? __headerAzureAsyncOperationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__proxyResource), __proxyResource); + await eventListener.AssertObjectIsValid(nameof(__proxyResource), __proxyResource); + } + } + /// Certificate profile resource. + public partial interface ICertificateProfile : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource + { + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Azure-AsyncOperation", + PossibleTypes = new [] { typeof(string) })] + string AzureAsyncOperation { get; set; } + /// List of renewed certificates. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of renewed certificates.", + SerializedName = @"certificates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate) })] + System.Collections.Generic.List Certificate { get; } + /// Used as L in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as L in the certificate subject name.", + SerializedName = @"city", + PossibleTypes = new [] { typeof(string) })] + string City { get; } + /// Used as CN in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as CN in the certificate subject name.", + SerializedName = @"commonName", + PossibleTypes = new [] { typeof(string) })] + string CommonName { get; } + /// Used as C in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as C in the certificate subject name.", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + string Country { get; } + /// Enhanced key usage of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Enhanced key usage of the certificate.", + SerializedName = @"enhancedKeyUsage", + PossibleTypes = new [] { typeof(string) })] + string EnhancedKeyUsage { get; } + /// Identity validation id used for the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + string IdentityValidationId { get; set; } + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeCity { get; set; } + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeCountry { get; set; } + /// Whether to include PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludePostalCode { get; set; } + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeState { get; set; } + /// Whether to include STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeStreetAddress { get; set; } + /// Used as O in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as O in the certificate subject name.", + SerializedName = @"organization", + PossibleTypes = new [] { typeof(string) })] + string Organization { get; } + /// Used as OU in the private trust certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as OU in the private trust certificate subject name.", + SerializedName = @"organizationUnit", + PossibleTypes = new [] { typeof(string) })] + string OrganizationUnit { get; } + /// Used as PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as PC in the certificate subject name.", + SerializedName = @"postalCode", + PossibleTypes = new [] { typeof(string) })] + string PostalCode { get; } + /// Profile type of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + string ProfileType { get; set; } + /// Status of the current operation on certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the current operation on certificate profile.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + /// Used as S in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as S in the certificate subject name.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string State { get; } + /// Status of the certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the certificate profile.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Disabled", "Suspended")] + string Status { get; } + /// Used as STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as STREET in the certificate subject name.", + SerializedName = @"streetAddress", + PossibleTypes = new [] { typeof(string) })] + string StreetAddress { get; } + + } + /// Certificate profile resource. + internal partial interface ICertificateProfileInternal : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResourceInternal + { + string AzureAsyncOperation { get; set; } + /// List of renewed certificates. + System.Collections.Generic.List Certificate { get; set; } + /// Used as L in the certificate subject name. + string City { get; set; } + /// Used as CN in the certificate subject name. + string CommonName { get; set; } + /// Used as C in the certificate subject name. + string Country { get; set; } + /// Enhanced key usage of the certificate. + string EnhancedKeyUsage { get; set; } + /// Identity validation id used for the certificate subject name. + string IdentityValidationId { get; set; } + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeCity { get; set; } + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeCountry { get; set; } + /// Whether to include PC in the certificate subject name. + bool? IncludePostalCode { get; set; } + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeState { get; set; } + /// Whether to include STREET in the certificate subject name. + bool? IncludeStreetAddress { get; set; } + /// Used as O in the certificate subject name. + string Organization { get; set; } + /// Used as OU in the private trust certificate subject name. + string OrganizationUnit { get; set; } + /// Used as PC in the certificate subject name. + string PostalCode { get; set; } + /// Profile type of the certificate. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + string ProfileType { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties Property { get; set; } + /// Status of the current operation on certificate profile. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; set; } + + int? RetryAfter { get; set; } + /// Used as S in the certificate subject name. + string State { get; set; } + /// Status of the certificate profile. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Disabled", "Suspended")] + string Status { get; set; } + /// Used as STREET in the certificate subject name. + string StreetAddress { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.json.cs new file mode 100644 index 00000000000..9470df8e5f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfile.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Certificate profile resource. + public partial class CertificateProfile + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CertificateProfile(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __proxyResource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ProxyResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CertificateProfile(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.PowerShell.cs new file mode 100644 index 00000000000..1ab7eacc181 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// The response of a CertificateProfile list operation. + [System.ComponentModel.TypeConverter(typeof(CertificateProfileListResultTypeConverter))] + public partial class CertificateProfileListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CertificateProfileListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CertificateProfileListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfileTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal)this).NextLink, 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.CodeSigning.Models.ICertificateProfileListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CertificateProfileListResult(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.CodeSigning.Models.ICertificateProfileListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CertificateProfileListResult(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.CodeSigning.Models.ICertificateProfileListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The response of a CertificateProfile list operation. + [System.ComponentModel.TypeConverter(typeof(CertificateProfileListResultTypeConverter))] + public partial interface ICertificateProfileListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.TypeConverter.cs new file mode 100644 index 00000000000..4f93628121a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CertificateProfileListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CertificateProfileListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CertificateProfileListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CertificateProfileListResult.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.cs new file mode 100644 index 00000000000..e22522d3b52 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The response of a CertificateProfile list operation. + public partial class CertificateProfileListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The CertificateProfile items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public CertificateProfileListResult() + { + + } + } + /// The response of a CertificateProfile list operation. + public partial interface ICertificateProfileListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The CertificateProfile items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The CertificateProfile items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a CertificateProfile list operation. + internal partial interface ICertificateProfileListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The CertificateProfile items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.json.cs new file mode 100644 index 00000000000..6a2b4b43641 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileListResult.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The response of a CertificateProfile list operation. + public partial class CertificateProfileListResult + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CertificateProfileListResult(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CertificateProfileListResult(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.PowerShell.cs new file mode 100644 index 00000000000..4abfd8bb030 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.PowerShell.cs @@ -0,0 +1,306 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Properties of the certificate profile. + [System.ComponentModel.TypeConverter(typeof(CertificateProfilePropertiesTypeConverter))] + public partial class CertificateProfileProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CertificateProfileProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProfileType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProfileType = (string) content.GetValueForProperty("ProfileType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProfileType, global::System.Convert.ToString); + } + if (content.Contains("CommonName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).CommonName = (string) content.GetValueForProperty("CommonName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).CommonName, global::System.Convert.ToString); + } + if (content.Contains("Organization")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Organization = (string) content.GetValueForProperty("Organization",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Organization, global::System.Convert.ToString); + } + if (content.Contains("OrganizationUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).OrganizationUnit = (string) content.GetValueForProperty("OrganizationUnit",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).OrganizationUnit, global::System.Convert.ToString); + } + if (content.Contains("StreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).StreetAddress = (string) content.GetValueForProperty("StreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).StreetAddress, global::System.Convert.ToString); + } + if (content.Contains("IncludeStreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeStreetAddress = (bool?) content.GetValueForProperty("IncludeStreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeStreetAddress, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("City")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).City = (string) content.GetValueForProperty("City",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).City, global::System.Convert.ToString); + } + if (content.Contains("IncludeCity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCity = (bool?) content.GetValueForProperty("IncludeCity",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCity, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("IncludeState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeState = (bool?) content.GetValueForProperty("IncludeState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeState, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("IncludeCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCountry = (bool?) content.GetValueForProperty("IncludeCountry",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCountry, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("PostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).PostalCode = (string) content.GetValueForProperty("PostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).PostalCode, global::System.Convert.ToString); + } + if (content.Contains("IncludePostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludePostalCode = (bool?) content.GetValueForProperty("IncludePostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludePostalCode, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnhancedKeyUsage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).EnhancedKeyUsage = (string) content.GetValueForProperty("EnhancedKeyUsage",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).EnhancedKeyUsage, global::System.Convert.ToString); + } + if (content.Contains("IdentityValidationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IdentityValidationId = (string) content.GetValueForProperty("IdentityValidationId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IdentityValidationId, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Certificate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Certificate = (System.Collections.Generic.List) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Certificate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CertificateProfileProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("ProfileType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProfileType = (string) content.GetValueForProperty("ProfileType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProfileType, global::System.Convert.ToString); + } + if (content.Contains("CommonName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).CommonName = (string) content.GetValueForProperty("CommonName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).CommonName, global::System.Convert.ToString); + } + if (content.Contains("Organization")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Organization = (string) content.GetValueForProperty("Organization",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Organization, global::System.Convert.ToString); + } + if (content.Contains("OrganizationUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).OrganizationUnit = (string) content.GetValueForProperty("OrganizationUnit",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).OrganizationUnit, global::System.Convert.ToString); + } + if (content.Contains("StreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).StreetAddress = (string) content.GetValueForProperty("StreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).StreetAddress, global::System.Convert.ToString); + } + if (content.Contains("IncludeStreetAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeStreetAddress = (bool?) content.GetValueForProperty("IncludeStreetAddress",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeStreetAddress, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("City")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).City = (string) content.GetValueForProperty("City",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).City, global::System.Convert.ToString); + } + if (content.Contains("IncludeCity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCity = (bool?) content.GetValueForProperty("IncludeCity",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCity, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("State")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).State = (string) content.GetValueForProperty("State",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).State, global::System.Convert.ToString); + } + if (content.Contains("IncludeState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeState = (bool?) content.GetValueForProperty("IncludeState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeState, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("IncludeCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCountry = (bool?) content.GetValueForProperty("IncludeCountry",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludeCountry, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("PostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).PostalCode = (string) content.GetValueForProperty("PostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).PostalCode, global::System.Convert.ToString); + } + if (content.Contains("IncludePostalCode")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludePostalCode = (bool?) content.GetValueForProperty("IncludePostalCode",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IncludePostalCode, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("EnhancedKeyUsage")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).EnhancedKeyUsage = (string) content.GetValueForProperty("EnhancedKeyUsage",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).EnhancedKeyUsage, global::System.Convert.ToString); + } + if (content.Contains("IdentityValidationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IdentityValidationId = (string) content.GetValueForProperty("IdentityValidationId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).IdentityValidationId, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("Certificate")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Certificate = (System.Collections.Generic.List) content.GetValueForProperty("Certificate",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal)this).Certificate, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateTypeConverter.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.CodeSigning.Models.ICertificateProfileProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CertificateProfileProperties(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.CodeSigning.Models.ICertificateProfileProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CertificateProfileProperties(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.CodeSigning.Models.ICertificateProfileProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties of the certificate profile. + [System.ComponentModel.TypeConverter(typeof(CertificateProfilePropertiesTypeConverter))] + public partial interface ICertificateProfileProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.TypeConverter.cs new file mode 100644 index 00000000000..eb727f06702 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CertificateProfilePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CertificateProfileProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CertificateProfileProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CertificateProfileProperties.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.cs new file mode 100644 index 00000000000..c897ade711e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.cs @@ -0,0 +1,472 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the certificate profile. + public partial class CertificateProfileProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _certificate; + + /// List of renewed certificates. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List Certificate { get => this._certificate; } + + /// Backing field for property. + private string _city; + + /// Used as L in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string City { get => this._city; } + + /// Backing field for property. + private string _commonName; + + /// Used as CN in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string CommonName { get => this._commonName; } + + /// Backing field for property. + private string _country; + + /// Used as C in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Country { get => this._country; } + + /// Backing field for property. + private string _enhancedKeyUsage; + + /// Enhanced key usage of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string EnhancedKeyUsage { get => this._enhancedKeyUsage; } + + /// Backing field for property. + private string _identityValidationId; + + /// Identity validation id used for the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string IdentityValidationId { get => this._identityValidationId; set => this._identityValidationId = value; } + + /// Backing field for property. + private bool? _includeCity; + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IncludeCity { get => this._includeCity; set => this._includeCity = value; } + + /// Backing field for property. + private bool? _includeCountry; + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IncludeCountry { get => this._includeCountry; set => this._includeCountry = value; } + + /// Backing field for property. + private bool? _includePostalCode; + + /// Whether to include PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IncludePostalCode { get => this._includePostalCode; set => this._includePostalCode = value; } + + /// Backing field for property. + private bool? _includeState; + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IncludeState { get => this._includeState; set => this._includeState = value; } + + /// Backing field for property. + private bool? _includeStreetAddress; + + /// Whether to include STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IncludeStreetAddress { get => this._includeStreetAddress; set => this._includeStreetAddress = value; } + + /// Internal Acessors for Certificate + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.Certificate { get => this._certificate; set { {_certificate = value;} } } + + /// Internal Acessors for City + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.City { get => this._city; set { {_city = value;} } } + + /// Internal Acessors for CommonName + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.CommonName { get => this._commonName; set { {_commonName = value;} } } + + /// Internal Acessors for Country + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.Country { get => this._country; set { {_country = value;} } } + + /// Internal Acessors for EnhancedKeyUsage + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.EnhancedKeyUsage { get => this._enhancedKeyUsage; set { {_enhancedKeyUsage = value;} } } + + /// Internal Acessors for Organization + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.Organization { get => this._organization; set { {_organization = value;} } } + + /// Internal Acessors for OrganizationUnit + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.OrganizationUnit { get => this._organizationUnit; set { {_organizationUnit = value;} } } + + /// Internal Acessors for PostalCode + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.PostalCode { get => this._postalCode; set { {_postalCode = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for State + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.State { get => this._state; set { {_state = value;} } } + + /// Internal Acessors for Status + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.Status { get => this._status; set { {_status = value;} } } + + /// Internal Acessors for StreetAddress + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilePropertiesInternal.StreetAddress { get => this._streetAddress; set { {_streetAddress = value;} } } + + /// Backing field for property. + private string _organization; + + /// Used as O in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Organization { get => this._organization; } + + /// Backing field for property. + private string _organizationUnit; + + /// Used as OU in the private trust certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string OrganizationUnit { get => this._organizationUnit; } + + /// Backing field for property. + private string _postalCode; + + /// Used as PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string PostalCode { get => this._postalCode; } + + /// Backing field for property. + private string _profileType; + + /// Profile type of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ProfileType { get => this._profileType; set => this._profileType = value; } + + /// Backing field for property. + private string _provisioningState; + + /// Status of the current operation on certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _state; + + /// Used as S in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string State { get => this._state; } + + /// Backing field for property. + private string _status; + + /// Status of the certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Status { get => this._status; } + + /// Backing field for property. + private string _streetAddress; + + /// Used as STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string StreetAddress { get => this._streetAddress; } + + /// Creates an new instance. + public CertificateProfileProperties() + { + + } + } + /// Properties of the certificate profile. + public partial interface ICertificateProfileProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// List of renewed certificates. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"List of renewed certificates.", + SerializedName = @"certificates", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate) })] + System.Collections.Generic.List Certificate { get; } + /// Used as L in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as L in the certificate subject name.", + SerializedName = @"city", + PossibleTypes = new [] { typeof(string) })] + string City { get; } + /// Used as CN in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as CN in the certificate subject name.", + SerializedName = @"commonName", + PossibleTypes = new [] { typeof(string) })] + string CommonName { get; } + /// Used as C in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as C in the certificate subject name.", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + string Country { get; } + /// Enhanced key usage of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Enhanced key usage of the certificate.", + SerializedName = @"enhancedKeyUsage", + PossibleTypes = new [] { typeof(string) })] + string EnhancedKeyUsage { get; } + /// Identity validation id used for the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + string IdentityValidationId { get; set; } + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeCity { get; set; } + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeCountry { get; set; } + /// Whether to include PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludePostalCode { get; set; } + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeState { get; set; } + /// Whether to include STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(bool) })] + bool? IncludeStreetAddress { get; set; } + /// Used as O in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as O in the certificate subject name.", + SerializedName = @"organization", + PossibleTypes = new [] { typeof(string) })] + string Organization { get; } + /// Used as OU in the private trust certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as OU in the private trust certificate subject name.", + SerializedName = @"organizationUnit", + PossibleTypes = new [] { typeof(string) })] + string OrganizationUnit { get; } + /// Used as PC in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as PC in the certificate subject name.", + SerializedName = @"postalCode", + PossibleTypes = new [] { typeof(string) })] + string PostalCode { get; } + /// Profile type of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + string ProfileType { get; set; } + /// Status of the current operation on certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the current operation on certificate profile.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; } + /// Used as S in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as S in the certificate subject name.", + SerializedName = @"state", + PossibleTypes = new [] { typeof(string) })] + string State { get; } + /// Status of the certificate profile. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the certificate profile.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Disabled", "Suspended")] + string Status { get; } + /// Used as STREET in the certificate subject name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Used as STREET in the certificate subject name.", + SerializedName = @"streetAddress", + PossibleTypes = new [] { typeof(string) })] + string StreetAddress { get; } + + } + /// Properties of the certificate profile. + internal partial interface ICertificateProfilePropertiesInternal + + { + /// List of renewed certificates. + System.Collections.Generic.List Certificate { get; set; } + /// Used as L in the certificate subject name. + string City { get; set; } + /// Used as CN in the certificate subject name. + string CommonName { get; set; } + /// Used as C in the certificate subject name. + string Country { get; set; } + /// Enhanced key usage of the certificate. + string EnhancedKeyUsage { get; set; } + /// Identity validation id used for the certificate subject name. + string IdentityValidationId { get; set; } + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeCity { get; set; } + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeCountry { get; set; } + /// Whether to include PC in the certificate subject name. + bool? IncludePostalCode { get; set; } + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + bool? IncludeState { get; set; } + /// Whether to include STREET in the certificate subject name. + bool? IncludeStreetAddress { get; set; } + /// Used as O in the certificate subject name. + string Organization { get; set; } + /// Used as OU in the private trust certificate subject name. + string OrganizationUnit { get; set; } + /// Used as PC in the certificate subject name. + string PostalCode { get; set; } + /// Profile type of the certificate. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + string ProfileType { get; set; } + /// Status of the current operation on certificate profile. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; set; } + /// Used as S in the certificate subject name. + string State { get; set; } + /// Status of the certificate profile. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Active", "Disabled", "Suspended")] + string Status { get; set; } + /// Used as STREET in the certificate subject name. + string StreetAddress { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.json.cs new file mode 100644 index 00000000000..36457160908 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfileProperties.json.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the certificate profile. + public partial class CertificateProfileProperties + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CertificateProfileProperties(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_profileType = If( json?.PropertyT("profileType"), out var __jsonProfileType) ? (string)__jsonProfileType : (string)_profileType;} + {_commonName = If( json?.PropertyT("commonName"), out var __jsonCommonName) ? (string)__jsonCommonName : (string)_commonName;} + {_organization = If( json?.PropertyT("organization"), out var __jsonOrganization) ? (string)__jsonOrganization : (string)_organization;} + {_organizationUnit = If( json?.PropertyT("organizationUnit"), out var __jsonOrganizationUnit) ? (string)__jsonOrganizationUnit : (string)_organizationUnit;} + {_streetAddress = If( json?.PropertyT("streetAddress"), out var __jsonStreetAddress) ? (string)__jsonStreetAddress : (string)_streetAddress;} + {_includeStreetAddress = If( json?.PropertyT("includeStreetAddress"), out var __jsonIncludeStreetAddress) ? (bool?)__jsonIncludeStreetAddress : _includeStreetAddress;} + {_city = If( json?.PropertyT("city"), out var __jsonCity) ? (string)__jsonCity : (string)_city;} + {_includeCity = If( json?.PropertyT("includeCity"), out var __jsonIncludeCity) ? (bool?)__jsonIncludeCity : _includeCity;} + {_state = If( json?.PropertyT("state"), out var __jsonState) ? (string)__jsonState : (string)_state;} + {_includeState = If( json?.PropertyT("includeState"), out var __jsonIncludeState) ? (bool?)__jsonIncludeState : _includeState;} + {_country = If( json?.PropertyT("country"), out var __jsonCountry) ? (string)__jsonCountry : (string)_country;} + {_includeCountry = If( json?.PropertyT("includeCountry"), out var __jsonIncludeCountry) ? (bool?)__jsonIncludeCountry : _includeCountry;} + {_postalCode = If( json?.PropertyT("postalCode"), out var __jsonPostalCode) ? (string)__jsonPostalCode : (string)_postalCode;} + {_includePostalCode = If( json?.PropertyT("includePostalCode"), out var __jsonIncludePostalCode) ? (bool?)__jsonIncludePostalCode : _includePostalCode;} + {_enhancedKeyUsage = If( json?.PropertyT("enhancedKeyUsage"), out var __jsonEnhancedKeyUsage) ? (string)__jsonEnhancedKeyUsage : (string)_enhancedKeyUsage;} + {_identityValidationId = If( json?.PropertyT("identityValidationId"), out var __jsonIdentityValidationId) ? (string)__jsonIdentityValidationId : (string)_identityValidationId;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_certificate = If( json?.PropertyT("certificates"), out var __jsonCertificates) ? If( __jsonCertificates as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificate) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Certificate.FromJson(__u) )) ))() : null : _certificate;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CertificateProfileProperties(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._profileType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._profileType.ToString()) : null, "profileType" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._commonName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._commonName.ToString()) : null, "commonName" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._organization)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._organization.ToString()) : null, "organization" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._organizationUnit)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._organizationUnit.ToString()) : null, "organizationUnit" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._streetAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._streetAddress.ToString()) : null, "streetAddress" ,container.Add ); + } + AddIf( null != this._includeStreetAddress ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._includeStreetAddress) : null, "includeStreetAddress" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._city)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._city.ToString()) : null, "city" ,container.Add ); + } + AddIf( null != this._includeCity ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._includeCity) : null, "includeCity" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._state)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._state.ToString()) : null, "state" ,container.Add ); + } + AddIf( null != this._includeState ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._includeState) : null, "includeState" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._country)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._country.ToString()) : null, "country" ,container.Add ); + } + AddIf( null != this._includeCountry ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._includeCountry) : null, "includeCountry" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._postalCode)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._postalCode.ToString()) : null, "postalCode" ,container.Add ); + } + AddIf( null != this._includePostalCode ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._includePostalCode) : null, "includePostalCode" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._enhancedKeyUsage)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._enhancedKeyUsage.ToString()) : null, "enhancedKeyUsage" ,container.Add ); + } + AddIf( null != (((object)this._identityValidationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._identityValidationId.ToString()) : null, "identityValidationId" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._certificate) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __x in this._certificate ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("certificates",__w); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..e3f0a03abcc --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(CertificateProfilesDeleteAcceptedResponseHeadersTypeConverter))] + public partial class CertificateProfilesDeleteAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CertificateProfilesDeleteAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CertificateProfilesDeleteAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CertificateProfilesDeleteAcceptedResponseHeaders(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.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CertificateProfilesDeleteAcceptedResponseHeaders(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.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(CertificateProfilesDeleteAcceptedResponseHeadersTypeConverter))] + public partial interface ICertificateProfilesDeleteAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..1c033089216 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CertificateProfilesDeleteAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, + /// otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CertificateProfilesDeleteAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CertificateProfilesDeleteAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CertificateProfilesDeleteAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..f6328705a36 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CertificateProfilesDeleteAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + /// Creates an new instance. + /// + public CertificateProfilesDeleteAcceptedResponseHeaders() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + } + public partial interface ICertificateProfilesDeleteAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface ICertificateProfilesDeleteAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..80c2f8ddb4f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CertificateProfilesDeleteAcceptedResponseHeaders.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CertificateProfilesDeleteAcceptedResponseHeaders + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CertificateProfilesDeleteAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfilesDeleteAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CertificateProfilesDeleteAcceptedResponseHeaders(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.PowerShell.cs new file mode 100644 index 00000000000..5647369efdf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.PowerShell.cs @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// The parameters used to check the availability of the trusted signing account name. + /// + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityTypeConverter))] + public partial class CheckNameAvailability + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CheckNameAvailability(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityInternal)this).Name, 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 CheckNameAvailability(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityInternal)this).Name, 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.CodeSigning.Models.ICheckNameAvailability DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CheckNameAvailability(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.CodeSigning.Models.ICheckNameAvailability DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CheckNameAvailability(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.CodeSigning.Models.ICheckNameAvailability FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The parameters used to check the availability of the trusted signing account name. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityTypeConverter))] + public partial interface ICheckNameAvailability + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.TypeConverter.cs new file mode 100644 index 00000000000..e0417ecbb14 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CheckNameAvailabilityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CheckNameAvailability.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CheckNameAvailability.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CheckNameAvailability.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.cs new file mode 100644 index 00000000000..e292c78cd46 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The parameters used to check the availability of the trusted signing account name. + /// + public partial class CheckNameAvailability : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityInternal + { + + /// Backing field for property. + private string _name; + + /// Trusted signing account name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Name { get => this._name; set => this._name = value; } + + /// Creates an new instance. + public CheckNameAvailability() + { + + } + } + /// The parameters used to check the availability of the trusted signing account name. + public partial interface ICheckNameAvailability : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Trusted signing account name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Trusted signing account name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; set; } + + } + /// The parameters used to check the availability of the trusted signing account name. + internal partial interface ICheckNameAvailabilityInternal + + { + /// Trusted signing account name. + string Name { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.json.cs new file mode 100644 index 00000000000..f77ed7da0ff --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailability.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The parameters used to check the availability of the trusted signing account name. + /// + public partial class CheckNameAvailability + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailability(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CheckNameAvailability(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.PowerShell.cs new file mode 100644 index 00000000000..1b9e1b9243b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.PowerShell.cs @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CheckNameAvailabilityResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NameAvailable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)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 CheckNameAvailabilityResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("NameAvailable")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).NameAvailable = (bool?) content.GetValueForProperty("NameAvailable",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).NameAvailable, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal)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.CodeSigning.Models.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.CodeSigning.Models.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.CodeSigning.Models.ICheckNameAvailabilityResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The CheckNameAvailability operation response. + [System.ComponentModel.TypeConverter(typeof(CheckNameAvailabilityResultTypeConverter))] + public partial interface ICheckNameAvailabilityResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.TypeConverter.cs new file mode 100644 index 00000000000..939f7cd787c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.cs new file mode 100644 index 00000000000..b3bdaab8a67 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The CheckNameAvailability operation response. + public partial class CheckNameAvailabilityResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal + { + + /// Backing field for property. + private string _message; + + /// An error message explaining the Reason value in more detail. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for NameAvailable + bool? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResultInternal.NameAvailable { get => this._nameAvailable; set { {_nameAvailable = value;} } } + + /// Internal Acessors for Reason + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? NameAvailable { get => this._nameAvailable; } + + /// Backing field for property. + private string _reason; + + /// + /// The reason that a trusted signing account name could not be used. The Reason element is only returned if nameAvailable + /// is false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Reason { get => this._reason; } + + /// Creates an new instance. + public CheckNameAvailabilityResult() + { + + } + } + /// The CheckNameAvailability operation response. + public partial interface ICheckNameAvailabilityResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// An error message explaining the Reason value in more detail. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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 trusted signing account name could not be used. The Reason element is only returned if nameAvailable + /// is false. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The reason that a trusted signing account name could not be used. The Reason element is only returned if nameAvailable is false.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("AccountNameInvalid", "AlreadyExists")] + string 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 trusted signing account name could not be used. The Reason element is only returned if nameAvailable + /// is false. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("AccountNameInvalid", "AlreadyExists")] + string Reason { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.json.cs new file mode 100644 index 00000000000..8345dfb3f28 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CheckNameAvailabilityResult.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CheckNameAvailabilityResult(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_nameAvailable = If( json?.PropertyT("nameAvailable"), out var __jsonNameAvailable) ? (bool?)__jsonNameAvailable : _nameAvailable;} + {_reason = If( json?.PropertyT("reason"), out var __jsonReason) ? (string)__jsonReason : (string)_reason;} + {_message = If( json?.PropertyT("message"), out var __jsonMessage) ? (string)__jsonMessage : (string)_message;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._nameAvailable ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._nameAvailable) : null, "nameAvailable" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.PowerShell.cs new file mode 100644 index 00000000000..9579331bc87 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.PowerShell.cs @@ -0,0 +1,306 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Trusted signing account resource. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountTypeConverter))] + public partial class CodeSigningAccount + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccount(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("AccountUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AccountUri = (string) content.GetValueForProperty("AccountUri",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AccountUri, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).SkuName, 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 CodeSigningAccount(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("AccountUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AccountUri = (string) content.GetValueForProperty("AccountUri",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AccountUri, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).SkuName, 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.CodeSigning.Models.ICodeSigningAccount DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccount(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.CodeSigning.Models.ICodeSigningAccount DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccount(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.CodeSigning.Models.ICodeSigningAccount FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Trusted signing account resource. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountTypeConverter))] + public partial interface ICodeSigningAccount + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.TypeConverter.cs new file mode 100644 index 00000000000..c4561afbd10 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccount.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccount.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccount.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.cs new file mode 100644 index 00000000000..81e100448c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.cs @@ -0,0 +1,251 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Trusted signing account resource. + public partial class CodeSigningAccount : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IValidates, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TrackedResource(); + + /// The URI of the trusted signing account which is used during signing files. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string AccountUri { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).AccountUri; } + + /// Backing field for property. + private string _azureAsyncOperation; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string AzureAsyncOperation { get => this._azureAsyncOperation; set => this._azureAsyncOperation = value; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)__trackedResource).Location = value ; } + + /// Internal Acessors for AccountUri + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal.AccountUri { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).AccountUri; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).AccountUri = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal.Sku { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).Sku; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).Sku = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountProperties()); set => this._property = value; } + + /// Status of the current operation on trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).SkuName; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)Property).SkuName = value ?? null; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)__trackedResource).Tag = value ?? null /* model class */; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__trackedResource).Type; } + + /// Creates an new instance. + public CodeSigningAccount() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Azure-AsyncOperation", out var __azureAsyncOperationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).AzureAsyncOperation = System.Linq.Enumerable.FirstOrDefault(__azureAsyncOperationHeader0) is string __headerAzureAsyncOperationHeader0 ? __headerAzureAsyncOperationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Trusted signing account resource. + public partial interface ICodeSigningAccount : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource + { + /// The URI of the trusted signing account which is used during signing files. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The URI of the trusted signing account which is used during signing files.", + SerializedName = @"accountUri", + PossibleTypes = new [] { typeof(string) })] + string AccountUri { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Azure-AsyncOperation", + PossibleTypes = new [] { typeof(string) })] + string AzureAsyncOperation { get; set; } + /// Status of the current operation on trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the current operation on trusted signing account.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } + /// Trusted signing account resource. + internal partial interface ICodeSigningAccountInternal : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal + { + /// The URI of the trusted signing account which is used during signing files. + string AccountUri { get; set; } + + string AzureAsyncOperation { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties Property { get; set; } + /// Status of the current operation on trusted signing account. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; set; } + + int? RetryAfter { get; set; } + /// SKU of the trusted signing account. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get; set; } + /// Name of the SKU. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.json.cs new file mode 100644 index 00000000000..cb05f9c6ca8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccount.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Trusted signing account resource. + public partial class CodeSigningAccount + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccount(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountProperties.FromJson(__jsonProperties) : _property;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccount(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.PowerShell.cs new file mode 100644 index 00000000000..4f82288f7f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// The response of a CodeSigningAccount list operation. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountListResultTypeConverter))] + public partial class CodeSigningAccountListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CodeSigningAccountListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal)this).NextLink, 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.CodeSigning.Models.ICodeSigningAccountListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountListResult(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.CodeSigning.Models.ICodeSigningAccountListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountListResult(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.CodeSigning.Models.ICodeSigningAccountListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The response of a CodeSigningAccount list operation. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountListResultTypeConverter))] + public partial interface ICodeSigningAccountListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.TypeConverter.cs new file mode 100644 index 00000000000..8598324fd2d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountListResult.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.cs new file mode 100644 index 00000000000..aa63e601d68 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The response of a CodeSigningAccount list operation. + public partial class CodeSigningAccountListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The CodeSigningAccount items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public CodeSigningAccountListResult() + { + + } + } + /// The response of a CodeSigningAccount list operation. + public partial interface ICodeSigningAccountListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The CodeSigningAccount items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The CodeSigningAccount items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a CodeSigningAccount list operation. + internal partial interface ICodeSigningAccountListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The CodeSigningAccount items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.json.cs new file mode 100644 index 00000000000..f2811235646 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountListResult.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The response of a CodeSigningAccount list operation. + public partial class CodeSigningAccountListResult + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountListResult(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountListResult(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.PowerShell.cs new file mode 100644 index 00000000000..a9d3c4ef8d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Parameters for creating or updating a trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPatchTypeConverter))] + public partial class CodeSigningAccountPatch + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountPatch(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatchPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).SkuName, 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 CodeSigningAccountPatch(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatchPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal)this).SkuName, 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.CodeSigning.Models.ICodeSigningAccountPatch DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountPatch(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.CodeSigning.Models.ICodeSigningAccountPatch DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountPatch(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.CodeSigning.Models.ICodeSigningAccountPatch FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Parameters for creating or updating a trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPatchTypeConverter))] + public partial interface ICodeSigningAccountPatch + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.TypeConverter.cs new file mode 100644 index 00000000000..b231f4c64b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountPatchTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountPatch.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountPatch.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountPatch.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.cs new file mode 100644 index 00000000000..92d29e9d74c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Parameters for creating or updating a trusted signing account. + public partial class CodeSigningAccountPatch : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal + { + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatchProperties()); set { {_property = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchInternal.Sku { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)Property).Sku; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)Property).Sku = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties _property; + + /// Properties of the trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatchProperties()); set => this._property = value; } + + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)Property).SkuName; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)Property).SkuName = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Tags()); set => this._tag = value; } + + /// Creates an new instance. + public CodeSigningAccountPatch() + { + + } + } + /// Parameters for creating or updating a trusted signing account. + public partial interface ICodeSigningAccountPatch : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get; set; } + + } + /// Parameters for creating or updating a trusted signing account. + internal partial interface ICodeSigningAccountPatchInternal + + { + /// Properties of the trusted signing account. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties Property { get; set; } + /// SKU of the trusted signing account. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get; set; } + /// Name of the SKU. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.json.cs new file mode 100644 index 00000000000..b49d12f357c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatch.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Parameters for creating or updating a trusted signing account. + public partial class CodeSigningAccountPatch + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountPatch(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models.CodeSigningAccountPatchProperties.FromJson(__jsonProperties) : _property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Tags.FromJson(__jsonTags) : _tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountPatch(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.PowerShell.cs new file mode 100644 index 00000000000..17ac80bf8da --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.PowerShell.cs @@ -0,0 +1,172 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Properties of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPatchPropertiesTypeConverter))] + public partial class CodeSigningAccountPatchProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountPatchProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).SkuName, 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 CodeSigningAccountPatchProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal)this).SkuName, 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.CodeSigning.Models.ICodeSigningAccountPatchProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountPatchProperties(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.CodeSigning.Models.ICodeSigningAccountPatchProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountPatchProperties(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.CodeSigning.Models.ICodeSigningAccountPatchProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPatchPropertiesTypeConverter))] + public partial interface ICodeSigningAccountPatchProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.TypeConverter.cs new file mode 100644 index 00000000000..20eb289974c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.TypeConverter.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountPatchPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountPatchProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountPatchProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountPatchProperties.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.cs new file mode 100644 index 00000000000..d0172e52dd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the trusted signing account. + public partial class CodeSigningAccountPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal + { + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchPropertiesInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSku()); set { {_sku = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku _sku; + + /// SKU of the trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSku()); set => this._sku = value; } + + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)Sku).Name = value ?? null; } + + /// Creates an new instance. + public CodeSigningAccountPatchProperties() + { + + } + } + /// Properties of the trusted signing account. + public partial interface ICodeSigningAccountPatchProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } + /// Properties of the trusted signing account. + internal partial interface ICodeSigningAccountPatchPropertiesInternal + + { + /// SKU of the trusted signing account. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get; set; } + /// Name of the SKU. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.json.cs new file mode 100644 index 00000000000..843caf6bd56 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountPatchProperties.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the trusted signing account. + public partial class CodeSigningAccountPatchProperties + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountPatchProperties(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models.AccountSku.FromJson(__jsonSku) : _sku;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatchProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountPatchProperties(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.PowerShell.cs new file mode 100644 index 00000000000..efab35f6213 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Properties of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPropertiesTypeConverter))] + public partial class CodeSigningAccountProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("AccountUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).AccountUri = (string) content.GetValueForProperty("AccountUri",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).AccountUri, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).SkuName, 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 CodeSigningAccountProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Sku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).Sku = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku) content.GetValueForProperty("Sku",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).Sku, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSkuTypeConverter.ConvertFrom); + } + if (content.Contains("AccountUri")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).AccountUri = (string) content.GetValueForProperty("AccountUri",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).AccountUri, global::System.Convert.ToString); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("SkuName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).SkuName = (string) content.GetValueForProperty("SkuName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal)this).SkuName, 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.CodeSigning.Models.ICodeSigningAccountProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountProperties(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.CodeSigning.Models.ICodeSigningAccountProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountProperties(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.CodeSigning.Models.ICodeSigningAccountProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties of the trusted signing account. + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountPropertiesTypeConverter))] + public partial interface ICodeSigningAccountProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.TypeConverter.cs new file mode 100644 index 00000000000..8ad2f494e0e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountProperties.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.cs new file mode 100644 index 00000000000..991ec4107fb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the trusted signing account. + public partial class CodeSigningAccountProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal + { + + /// Backing field for property. + private string _accountUri; + + /// The URI of the trusted signing account which is used during signing files. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string AccountUri { get => this._accountUri; } + + /// Internal Acessors for AccountUri + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal.AccountUri { get => this._accountUri; set { {_accountUri = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for Sku + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPropertiesInternal.Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSku()); set { {_sku = value;} } } + + /// Backing field for property. + private string _provisioningState; + + /// Status of the current operation on trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku _sku; + + /// SKU of the trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get => (this._sku = this._sku ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AccountSku()); set => this._sku = value; } + + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SkuName { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)Sku).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSkuInternal)Sku).Name = value ?? null; } + + /// Creates an new instance. + public CodeSigningAccountProperties() + { + + } + } + /// Properties of the trusted signing account. + public partial interface ICodeSigningAccountProperties : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The URI of the trusted signing account which is used during signing files. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The URI of the trusted signing account which is used during signing files.", + SerializedName = @"accountUri", + PossibleTypes = new [] { typeof(string) })] + string AccountUri { get; } + /// Status of the current operation on trusted signing account. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Status of the current operation on trusted signing account.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; } + /// Name of the SKU. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } + /// Properties of the trusted signing account. + internal partial interface ICodeSigningAccountPropertiesInternal + + { + /// The URI of the trusted signing account which is used during signing files. + string AccountUri { get; set; } + /// Status of the current operation on trusted signing account. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled", "Updating", "Deleting", "Accepted")] + string ProvisioningState { get; set; } + /// SKU of the trusted signing account. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAccountSku Sku { get; set; } + /// Name of the SKU. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + string SkuName { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.json.cs new file mode 100644 index 00000000000..ebbaf4d134a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountProperties.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Properties of the trusted signing account. + public partial class CodeSigningAccountProperties + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountProperties(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models.AccountSku.FromJson(__jsonSku) : _sku;} + {_accountUri = If( json?.PropertyT("accountUri"), out var __jsonAccountUri) ? (string)__jsonAccountUri : (string)_accountUri;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountProperties(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._sku ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._sku.ToJson(null,serializationMode) : null, "sku" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._accountUri)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._accountUri.ToString()) : null, "accountUri" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..0a38514344d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountsDeleteAcceptedResponseHeadersTypeConverter))] + public partial class CodeSigningAccountsDeleteAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountsDeleteAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CodeSigningAccountsDeleteAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountsDeleteAcceptedResponseHeaders(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.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountsDeleteAcceptedResponseHeaders(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.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountsDeleteAcceptedResponseHeadersTypeConverter))] + public partial interface ICodeSigningAccountsDeleteAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..28524f79bfd --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountsDeleteAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, + /// otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountsDeleteAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountsDeleteAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountsDeleteAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..113b9f57aa4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningAccountsDeleteAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + /// Creates an new instance. + /// + public CodeSigningAccountsDeleteAcceptedResponseHeaders() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + } + public partial interface ICodeSigningAccountsDeleteAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface ICodeSigningAccountsDeleteAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..18e19255dc8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsDeleteAcceptedResponseHeaders.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningAccountsDeleteAcceptedResponseHeaders + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountsDeleteAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsDeleteAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountsDeleteAcceptedResponseHeaders(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..8f592f86ea2 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountsUpdateAcceptedResponseHeadersTypeConverter))] + public partial class CodeSigningAccountsUpdateAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningAccountsUpdateAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CodeSigningAccountsUpdateAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningAccountsUpdateAcceptedResponseHeaders(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.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningAccountsUpdateAcceptedResponseHeaders(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.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(CodeSigningAccountsUpdateAcceptedResponseHeadersTypeConverter))] + public partial interface ICodeSigningAccountsUpdateAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..3bc93219514 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningAccountsUpdateAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, + /// otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable + /// conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningAccountsUpdateAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningAccountsUpdateAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningAccountsUpdateAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..a057f05aeb7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningAccountsUpdateAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + /// Creates an new instance. + /// + public CodeSigningAccountsUpdateAcceptedResponseHeaders() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + } + public partial interface ICodeSigningAccountsUpdateAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface ICodeSigningAccountsUpdateAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..7cfba3b780a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningAccountsUpdateAcceptedResponseHeaders.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningAccountsUpdateAcceptedResponseHeaders + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningAccountsUpdateAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountsUpdateAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningAccountsUpdateAcceptedResponseHeaders(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.PowerShell.cs new file mode 100644 index 00000000000..c871fccd17b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.PowerShell.cs @@ -0,0 +1,192 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(CodeSigningIdentityTypeConverter))] + public partial class CodeSigningIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CodeSigningIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("AccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).AccountName = (string) content.GetValueForProperty("AccountName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).AccountName, global::System.Convert.ToString); + } + if (content.Contains("ProfileName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ProfileName = (string) content.GetValueForProperty("ProfileName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ProfileName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)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 CodeSigningIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("AccountName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).AccountName = (string) content.GetValueForProperty("AccountName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).AccountName, global::System.Convert.ToString); + } + if (content.Contains("ProfileName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ProfileName = (string) content.GetValueForProperty("ProfileName",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).ProfileName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal)this).Id, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CodeSigningIdentity(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.CodeSigning.Models.ICodeSigningIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CodeSigningIdentity(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.CodeSigning.Models.ICodeSigningIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(CodeSigningIdentityTypeConverter))] + public partial interface ICodeSigningIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.TypeConverter.cs new file mode 100644 index 00000000000..3361ec370f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.TypeConverter.cs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CodeSigningIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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 CodeSigningIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CodeSigningIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CodeSigningIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CodeSigningIdentity.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.cs new file mode 100644 index 00000000000..045aa0e6bde --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.cs @@ -0,0 +1,129 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningIdentity : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentityInternal + { + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string AccountName { get => this._accountName; set => this._accountName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ProfileName { get => this._profileName; set => this._profileName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public CodeSigningIdentity() + { + + } + } + public partial interface ICodeSigningIdentity : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// Trusted Signing account name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + string AccountName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Certificate profile name. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + string ProfileName { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + 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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface ICodeSigningIdentityInternal + + { + /// Trusted Signing account name. + string AccountName { get; set; } + /// Resource identity path + string Id { get; set; } + /// Certificate profile name. + string ProfileName { get; set; } + /// The name of the resource group. The name is case insensitive. + string ResourceGroupName { get; set; } + /// The ID of the target subscription. The value must be an UUID. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.json.cs new file mode 100644 index 00000000000..b9ad59de004 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/CodeSigningIdentity.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class CodeSigningIdentity + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal CodeSigningIdentity(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)_resourceGroupName;} + {_accountName = If( json?.PropertyT("accountName"), out var __jsonAccountName) ? (string)__jsonAccountName : (string)_accountName;} + {_profileName = If( json?.PropertyT("profileName"), out var __jsonProfileName) ? (string)__jsonProfileName : (string)_profileName;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new CodeSigningIdentity(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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._accountName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._accountName.ToString()) : null, "accountName" ,container.Add ); + AddIf( null != (((object)this._profileName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._profileName.ToString()) : null, "profileName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..5c082a53f4d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial class ErrorAdditionalInfo + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorAdditionalInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorAdditionalInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial interface IErrorAdditionalInfo + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..2992a367cdc --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorAdditionalInfoTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorAdditionalInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..a10e7c47791 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorAdditionalInfo() + { + + } + } + /// The resource management error additional info. + public partial interface IErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info.", + SerializedName = @"info", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource management error additional info. + internal partial interface IErrorAdditionalInfoInternal + + { + /// The additional info. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IAny Info { get; set; } + /// The additional info type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..81e6e4a2512 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorAdditionalInfo.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_info = If( json?.PropertyT("info"), out var __jsonInfo) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new ErrorAdditionalInfo(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._info.ToJson(null,serializationMode) : null, "info" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..3346b80ce08 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial class ErrorDetail + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetail(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetail(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial interface IErrorDetail + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..fb66039372e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetail.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..1f680709158 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List AdditionalInfo { get => this._additionalInfo; } + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Creates an new instance. + public ErrorDetail() + { + + } + } + /// The error detail. + public partial interface IErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// The error detail. + internal partial interface IErrorDetailInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..13a78f2f3b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorDetail.json.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new ErrorDetail(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __s in this._additionalInfo ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("additionalInfo",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..cf35bba7d93 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial class ErrorResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Target, 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 + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal)this).Target, 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.CodeSigning.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..73224579b8f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..447202dee15 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).AdditionalInfo = value; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Code = value; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Message = value; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Target = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + internal partial interface IErrorResponseInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..99f022c2c6b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ErrorResponse.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..7a6705ca8c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.PowerShell.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial class Operation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Operation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Operation(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Operation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..59c41060355 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Operation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Operation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..ce49d3a576c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal + { + + /// Backing field for property. + private string _actionType; + + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; set => this._actionType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationDisplay()); } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Description; } + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Operation; } + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Provider; } + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Resource; } + + /// Backing field for property. + private bool? _isDataAction; + + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Extensible enum. Indicates the action type. ""Internal"" refers to actions that are for internal only APIs.", + SerializedName = @"actionType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Whether the operation applies to data-plane. This is ""true"" for data-plane operations and ""false"" for Azure Resource Manager/control-plane operations.", + SerializedName = @"isDataAction", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDataAction { get; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the operation, as per Resource-Based Access Control (RBAC). Examples: ""Microsoft.Compute/virtualMachines/write"", ""Microsoft.Compute/virtualMachines/capture/action""", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is ""user,system""", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; } + + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + internal partial interface IOperationInternal + + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay Display { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string DisplayOperation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string DisplayResource { get; set; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + bool? IsDataAction { get; set; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + string Name { get; set; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..0e28e1b0529 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Operation.json.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models.OperationDisplay.FromJson(__jsonDisplay) : _display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_isDataAction = If( json?.PropertyT("isDataAction"), out var __jsonIsDataAction) ? (bool?)__jsonIsDataAction : _isDataAction;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)_origin;} + {_actionType = If( json?.PropertyT("actionType"), out var __jsonActionType) ? (string)__jsonActionType : (string)_actionType;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._actionType.ToString()) : null, "actionType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..181ded2ac36 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial class OperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDisplay(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDisplay(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..af640994b35 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..93185fe9b2d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Localized display information for and operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Localized display information for and operation. + internal partial interface IOperationDisplayInternal + + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string Description { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string Operation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string Provider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..24d6f951a5c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationDisplay.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Localized display information for and 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)_provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)_resource;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)_operation;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..7e75f0f5487 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial class OperationListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..612c2bd2213 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..ce6cc030f9b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Operation items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation) })] + System.Collections.Generic.List Value { get; set; } + + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + internal partial interface IOperationListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Operation items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..6ca9746ffd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/OperationListResult.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Operation.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.PowerShell.cs new file mode 100644 index 00000000000..7a7705c220a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial class ProxyResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ProxyResource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ProxyResource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ProxyResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ProxyResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + [System.ComponentModel.TypeConverter(typeof(ProxyResourceTypeConverter))] + public partial interface IProxyResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.TypeConverter.cs new file mode 100644 index 00000000000..c2a213e364b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ProxyResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ProxyResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ProxyResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ProxyResource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.cs new file mode 100644 index 00000000000..355c9787b23 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + public partial class ProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Type; } + + /// Creates an new instance. + public ProxyResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + public partial interface IProxyResource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource + { + + } + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + internal partial interface IProxyResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.json.cs new file mode 100644 index 00000000000..eb91165d62f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/ProxyResource.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location + /// + public partial class ProxyResource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IProxyResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new ProxyResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal ProxyResource(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Resource(json); + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..ff27f32da65 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Resource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Resource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..ed38bc42b2a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Resource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Resource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Resource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..acda7e12266 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.cs @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataLastModifiedBy { get; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of the resource. E.g. ""Microsoft.Compute/virtualMachines"" or ""Microsoft.Storage/storageAccounts""", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get; set; } + /// The timestamp of resource creation (UTC). + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// The identity that last modified the resource. + string SystemDataLastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..0f2c9b357d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Resource.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.PowerShell.cs new file mode 100644 index 00000000000..aa60dafb9ab --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Revocation details of the certificate. + [System.ComponentModel.TypeConverter(typeof(RevocationTypeConverter))] + public partial class Revocation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Revocation(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.CodeSigning.Models.IRevocation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Revocation(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.CodeSigning.Models.IRevocation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Revocation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RequestedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).RequestedAt = (global::System.DateTime?) content.GetValueForProperty("RequestedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).RequestedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).EffectiveAt = (global::System.DateTime?) content.GetValueForProperty("EffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).EffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Remark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Remark = (string) content.GetValueForProperty("Remark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Remark, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).FailureReason, 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 Revocation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("RequestedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).RequestedAt = (global::System.DateTime?) content.GetValueForProperty("RequestedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).RequestedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("EffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).EffectiveAt = (global::System.DateTime?) content.GetValueForProperty("EffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).EffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Remark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Remark = (string) content.GetValueForProperty("Remark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Remark, global::System.Convert.ToString); + } + if (content.Contains("Status")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Status = (string) content.GetValueForProperty("Status",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).Status, global::System.Convert.ToString); + } + if (content.Contains("FailureReason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).FailureReason = (string) content.GetValueForProperty("FailureReason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal)this).FailureReason, 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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Revocation details of the certificate. + [System.ComponentModel.TypeConverter(typeof(RevocationTypeConverter))] + public partial interface IRevocation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.TypeConverter.cs new file mode 100644 index 00000000000..0b70a51187b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RevocationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Revocation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Revocation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Revocation.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.cs new file mode 100644 index 00000000000..a47e159018e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Revocation details of the certificate. + public partial class Revocation : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocationInternal + { + + /// Backing field for property. + private global::System.DateTime? _effectiveAt; + + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public global::System.DateTime? EffectiveAt { get => this._effectiveAt; set => this._effectiveAt = value; } + + /// Backing field for property. + private string _failureReason; + + /// Reason for the revocation failure. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string FailureReason { get => this._failureReason; set => this._failureReason = value; } + + /// Backing field for property. + private string _reason; + + /// Reason for revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Reason { get => this._reason; set => this._reason = value; } + + /// Backing field for property. + private string _remark; + + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Remark { get => this._remark; set => this._remark = value; } + + /// Backing field for property. + private global::System.DateTime? _requestedAt; + + /// The timestamp when the revocation is requested. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public global::System.DateTime? RequestedAt { get => this._requestedAt; set => this._requestedAt = value; } + + /// Backing field for property. + private string _status; + + /// Status of the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Status { get => this._status; set => this._status = value; } + + /// Creates an new instance. + public Revocation() + { + + } + } + /// Revocation details of the certificate. + public partial interface IRevocation : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? EffectiveAt { get; set; } + /// Reason for the revocation failure. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Reason for the revocation failure.", + SerializedName = @"failureReason", + PossibleTypes = new [] { typeof(string) })] + string FailureReason { get; set; } + /// Reason for revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Reason for revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + string Reason { get; set; } + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + string Remark { get; set; } + /// The timestamp when the revocation is requested. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp when the revocation is requested.", + SerializedName = @"requestedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? RequestedAt { get; set; } + /// Status of the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Status of the revocation.", + SerializedName = @"status", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "InProgress", "Failed")] + string Status { get; set; } + + } + /// Revocation details of the certificate. + internal partial interface IRevocationInternal + + { + /// The timestamp when the revocation is effective. + global::System.DateTime? EffectiveAt { get; set; } + /// Reason for the revocation failure. + string FailureReason { get; set; } + /// Reason for revocation. + string Reason { get; set; } + /// Remarks for the revocation. + string Remark { get; set; } + /// The timestamp when the revocation is requested. + global::System.DateTime? RequestedAt { get; set; } + /// Status of the revocation. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Succeeded", "InProgress", "Failed")] + string Status { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.json.cs new file mode 100644 index 00000000000..d844014582f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Revocation.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Revocation details of the certificate. + public partial class Revocation + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevocation FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Revocation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal Revocation(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_requestedAt = If( json?.PropertyT("requestedAt"), out var __jsonRequestedAt) ? global::System.DateTime.TryParse((string)__jsonRequestedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonRequestedAtValue) ? __jsonRequestedAtValue : _requestedAt : _requestedAt;} + {_effectiveAt = If( json?.PropertyT("effectiveAt"), out var __jsonEffectiveAt) ? global::System.DateTime.TryParse((string)__jsonEffectiveAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEffectiveAtValue) ? __jsonEffectiveAtValue : _effectiveAt : _effectiveAt;} + {_reason = If( json?.PropertyT("reason"), out var __jsonReason) ? (string)__jsonReason : (string)_reason;} + {_remark = If( json?.PropertyT("remarks"), out var __jsonRemarks) ? (string)__jsonRemarks : (string)_remark;} + {_status = If( json?.PropertyT("status"), out var __jsonStatus) ? (string)__jsonStatus : (string)_status;} + {_failureReason = If( json?.PropertyT("failureReason"), out var __jsonFailureReason) ? (string)__jsonFailureReason : (string)_failureReason;} + 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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._requestedAt ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._requestedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "requestedAt" ,container.Add ); + AddIf( null != this._effectiveAt ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._effectiveAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "effectiveAt" ,container.Add ); + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + AddIf( null != (((object)this._remark)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._remark.ToString()) : null, "remarks" ,container.Add ); + AddIf( null != (((object)this._status)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._status.ToString()) : null, "status" ,container.Add ); + AddIf( null != (((object)this._failureReason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._failureReason.ToString()) : null, "failureReason" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.PowerShell.cs new file mode 100644 index 00000000000..53c392bb72f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Defines the certificate revocation properties. + [System.ComponentModel.TypeConverter(typeof(RevokeCertificateTypeConverter))] + public partial class RevokeCertificate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new RevokeCertificate(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.CodeSigning.Models.IRevokeCertificate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new RevokeCertificate(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.CodeSigning.Models.IRevokeCertificate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal RevokeCertificate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SerialNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).SerialNumber = (string) content.GetValueForProperty("SerialNumber",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).SerialNumber, global::System.Convert.ToString); + } + if (content.Contains("Thumbprint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Thumbprint = (string) content.GetValueForProperty("Thumbprint",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Thumbprint, global::System.Convert.ToString); + } + if (content.Contains("EffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).EffectiveAt = (global::System.DateTime) content.GetValueForProperty("EffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).EffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Remark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Remark = (string) content.GetValueForProperty("Remark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Remark, 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 RevokeCertificate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SerialNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).SerialNumber = (string) content.GetValueForProperty("SerialNumber",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).SerialNumber, global::System.Convert.ToString); + } + if (content.Contains("Thumbprint")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Thumbprint = (string) content.GetValueForProperty("Thumbprint",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Thumbprint, global::System.Convert.ToString); + } + if (content.Contains("EffectiveAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).EffectiveAt = (global::System.DateTime) content.GetValueForProperty("EffectiveAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).EffectiveAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("Reason")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Reason = (string) content.GetValueForProperty("Reason",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Reason, global::System.Convert.ToString); + } + if (content.Contains("Remark")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Remark = (string) content.GetValueForProperty("Remark",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal)this).Remark, 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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Defines the certificate revocation properties. + [System.ComponentModel.TypeConverter(typeof(RevokeCertificateTypeConverter))] + public partial interface IRevokeCertificate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.TypeConverter.cs new file mode 100644 index 00000000000..118c45cbd77 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class RevokeCertificateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return RevokeCertificate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return RevokeCertificate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return RevokeCertificate.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.cs new file mode 100644 index 00000000000..9c9a0302f4d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Defines the certificate revocation properties. + public partial class RevokeCertificate : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificateInternal + { + + /// Backing field for property. + private global::System.DateTime _effectiveAt; + + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public global::System.DateTime EffectiveAt { get => this._effectiveAt; set => this._effectiveAt = value; } + + /// Backing field for property. + private string _reason; + + /// Reason for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Reason { get => this._reason; set => this._reason = value; } + + /// Backing field for property. + private string _remark; + + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Remark { get => this._remark; set => this._remark = value; } + + /// Backing field for property. + private string _serialNumber; + + /// Serial number of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string SerialNumber { get => this._serialNumber; set => this._serialNumber = value; } + + /// Backing field for property. + private string _thumbprint; + + /// Thumbprint of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Thumbprint { get => this._thumbprint; set => this._thumbprint = value; } + + /// Creates an new instance. + public RevokeCertificate() + { + + } + } + /// Defines the certificate revocation properties. + public partial interface IRevokeCertificate : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The timestamp when the revocation is effective. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime EffectiveAt { get; set; } + /// Reason for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Reason for the revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + string Reason { get; set; } + /// Remarks for the revocation. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + string Remark { get; set; } + /// Serial number of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Serial number of the certificate.", + SerializedName = @"serialNumber", + PossibleTypes = new [] { typeof(string) })] + string SerialNumber { get; set; } + /// Thumbprint of the certificate. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Thumbprint of the certificate.", + SerializedName = @"thumbprint", + PossibleTypes = new [] { typeof(string) })] + string Thumbprint { get; set; } + + } + /// Defines the certificate revocation properties. + internal partial interface IRevokeCertificateInternal + + { + /// The timestamp when the revocation is effective. + global::System.DateTime EffectiveAt { get; set; } + /// Reason for the revocation. + string Reason { get; set; } + /// Remarks for the revocation. + string Remark { get; set; } + /// Serial number of the certificate. + string SerialNumber { get; set; } + /// Thumbprint of the certificate. + string Thumbprint { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.json.cs new file mode 100644 index 00000000000..95a75cd4b5e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/RevokeCertificate.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Defines the certificate revocation properties. + public partial class RevokeCertificate + { + + /// + /// 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new RevokeCertificate(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal RevokeCertificate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_serialNumber = If( json?.PropertyT("serialNumber"), out var __jsonSerialNumber) ? (string)__jsonSerialNumber : (string)_serialNumber;} + {_thumbprint = If( json?.PropertyT("thumbprint"), out var __jsonThumbprint) ? (string)__jsonThumbprint : (string)_thumbprint;} + {_effectiveAt = If( json?.PropertyT("effectiveAt"), out var __jsonEffectiveAt) ? global::System.DateTime.TryParse((string)__jsonEffectiveAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonEffectiveAtValue) ? __jsonEffectiveAtValue : _effectiveAt : _effectiveAt;} + {_reason = If( json?.PropertyT("reason"), out var __jsonReason) ? (string)__jsonReason : (string)_reason;} + {_remark = If( json?.PropertyT("remarks"), out var __jsonRemarks) ? (string)__jsonRemarks : (string)_remark;} + 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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._serialNumber)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._serialNumber.ToString()) : null, "serialNumber" ,container.Add ); + AddIf( null != (((object)this._thumbprint)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._thumbprint.ToString()) : null, "thumbprint" ,container.Add ); + AddIf( (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._effectiveAt.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)), "effectiveAt" ,container.Add ); + AddIf( null != (((object)this._reason)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._reason.ToString()) : null, "reason" ,container.Add ); + AddIf( null != (((object)this._remark)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._remark.ToString()) : null, "remarks" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..c01ffeaac5b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..b688332125e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..5b5f917f5d1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; set => this._createdAt = value; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; set => this._createdBy = value; } + + /// Backing field for property. + private string _createdByType; + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; set => this._createdByType = value; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; set => this._lastModifiedAt = value; } + + /// Backing field for property. + private string _lastModifiedBy; + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string LastModifiedBy { get => this._lastModifiedBy; set => this._lastModifiedBy = value; } + + /// Backing field for property. + private string _lastModifiedByType; + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string LastModifiedByType { get => this._lastModifiedByType; set => this._lastModifiedByType = value; } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp of resource creation (UTC). + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..c60b4474746 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/SystemData.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_lastModifiedBy = If( json?.PropertyT("lastModifiedBy"), out var __jsonLastModifiedBy) ? (string)__jsonLastModifiedBy : (string)_lastModifiedBy;} + {_lastModifiedByType = If( json?.PropertyT("lastModifiedByType"), out var __jsonLastModifiedByType) ? (string)__jsonLastModifiedByType : (string)_lastModifiedByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + AddIf( null != (((object)this._lastModifiedBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.PowerShell.cs new file mode 100644 index 00000000000..e3d46132489 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// Resource tags. + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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.CodeSigning.Models.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.CodeSigning.Models.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 + // 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 Tags(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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.TypeConverter.cs new file mode 100644 index 00000000000..d09b5141c4d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.cs new file mode 100644 index 00000000000..6e5afeb553f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Resource tags. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITagsInternal + { + + /// Creates an new instance. + public Tags() + { + + } + } + /// Resource tags. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.dictionary.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.dictionary.cs new file mode 100644 index 00000000000..089b5326771 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.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.CodeSigning.Models.Tags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.json.cs new file mode 100644 index 00000000000..8af2cc7f2ae --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/Tags.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// Resource tags. + 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags. + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..047ef4df994 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.PowerShell.cs @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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.CodeSigning.Models.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.CodeSigning.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// 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 + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..7f8ce03cdf3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..28c1b501140 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Tags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Origin(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.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 that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = 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.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get; set; } + + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..5da439bdfc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/api/Models/TrackedResource.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + 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.CodeSigning.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.Tags.FromJson(__jsonTags) : _tag;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_Get.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_Get.cs new file mode 100644 index 00000000000..52212564306 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_Get.cs @@ -0,0 +1,505 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Get a trusted Signing Account. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningAccount_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Get a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningAccount_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningAccount_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsGet(SubscriptionId, ResourceGroupName, AccountName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_GetViaIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_GetViaIdentity.cs new file mode 100644 index 00000000000..8931025cdba --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_GetViaIdentity.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Get a trusted Signing Account. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningAccount_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Get a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningAccount_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningAccount_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CodeSigningAccountsGetViaIdentity(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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CodeSigningAccountsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List.cs new file mode 100644 index 00000000000..fbe6bc68cba --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List.cs @@ -0,0 +1,518 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Lists trusted signing accounts within a resource group. + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningAccount_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Lists trusted signing accounts within a resource group.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningAccount_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningAccount_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult + /// 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.CodeSigning.Models.ICodeSigningAccountListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List1.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List1.cs new file mode 100644 index 00000000000..89c92892989 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningAccount_List1.cs @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Lists trusted signing accounts within a subscription. + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/codeSigningAccounts" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningAccount_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Lists trusted signing accounts within a subscription.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/codeSigningAccounts", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningAccount_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningAccount_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountListResult + /// 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.CodeSigning.Models.ICodeSigningAccountListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_Get.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_Get.cs new file mode 100644 index 00000000000..4db139d0db0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_Get.cs @@ -0,0 +1,519 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Get details of a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningCertificateProfile_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Get details of a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningCertificateProfile_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningCertificateProfile_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesGet(SubscriptionId, ResourceGroupName, AccountName, ProfileName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentity.cs new file mode 100644 index 00000000000..b38c50cec58 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentity.cs @@ -0,0 +1,487 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Get details of a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningCertificateProfile_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Get details of a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningCertificateProfile_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningCertificateProfile_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CertificateProfilesGetViaIdentity(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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CertificateProfilesGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount.cs new file mode 100644 index 00000000000..5110ae80a52 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Get details of a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Get details of a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public GetAzCodeSigningCertificateProfile_GetViaIdentityCodeSigningAccount() + { + + } + + /// 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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + await this.Client.CertificateProfilesGetViaIdentity(CodeSigningAccountInputObject.Id, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + await this.Client.CertificateProfilesGet(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_List.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_List.cs new file mode 100644 index 00000000000..397623454d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningCertificateProfile_List.cs @@ -0,0 +1,532 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// List certificate profiles under a trusted signing account. + /// + /// [OpenAPI] ListByCodeSigningAccount=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningCertificateProfile_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"List certificate profiles under a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningCertificateProfile_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningCertificateProfile_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesListByCodeSigningAccount(SubscriptionId, ResourceGroupName, AccountName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfileListResult + /// 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.CodeSigning.Models.ICertificateProfileListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesListByCodeSigningAccount_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningOperation_List.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningOperation_List.cs new file mode 100644 index 00000000000..3edd1170c95 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/GetAzCodeSigningOperation_List.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Microsoft.CodeSigning/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzCodeSigningOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/providers/Microsoft.CodeSigning/operations", ApiVersion = "2024-02-05-preview")] + public partial class GetAzCodeSigningOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzCodeSigningOperation_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.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IOperationListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateExpanded.cs new file mode 100644 index 00000000000..68fce4911b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateExpanded.cs @@ -0,0 +1,626 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a trusted Signing Account. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningAccount_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class NewAzCodeSigningAccount_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Trusted signing account resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + public string SkuName { get => _resourceBody.SkuName ?? null; set => _resourceBody.SkuName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningAccount_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningAccount_CreateExpanded Clone() + { + var clone = new NewAzCodeSigningAccount_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._resourceBody = this._resourceBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.AccountName = this.AccountName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningAccount_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCreate(SubscriptionId, ResourceGroupName, AccountName, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..79315714321 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaIdentityExpanded.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a trusted Signing Account. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningAccount_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class NewAzCodeSigningAccount_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Trusted signing account resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccount(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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 = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + public string SkuName { get => _resourceBody.SkuName ?? null; set => _resourceBody.SkuName = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningAccount_CreateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningAccount_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzCodeSigningAccount_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningAccount_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CodeSigningAccountsCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CodeSigningAccountsCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..b41ce5e87d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonFilePath.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a trusted Signing Account. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningAccount_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class NewAzCodeSigningAccount_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningAccount_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningAccount_CreateViaJsonFilePath Clone() + { + var clone = new NewAzCodeSigningAccount_CreateViaJsonFilePath(); + 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.AccountName = this.AccountName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningAccount_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCreateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonString.cs new file mode 100644 index 00000000000..92deb453c41 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningAccount_CreateViaJsonString.cs @@ -0,0 +1,602 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a trusted Signing Account. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningAccount_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a trusted Signing Account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class NewAzCodeSigningAccount_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningAccount_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningAccount_CreateViaJsonString Clone() + { + var clone = new NewAzCodeSigningAccount_CreateViaJsonString(); + 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.AccountName = this.AccountName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningAccount_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCreateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateExpanded.cs new file mode 100644 index 00000000000..82b64a4290e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateExpanded.cs @@ -0,0 +1,690 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a certificate profile. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningCertificateProfile_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class NewAzCodeSigningCertificateProfile_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = value; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningCertificateProfile_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningCertificateProfile_CreateExpanded Clone() + { + var clone = new NewAzCodeSigningCertificateProfile_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._resourceBody = this._resourceBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.AccountName = this.AccountName; + clone.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningCertificateProfile_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesCreate(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded.cs new file mode 100644 index 00000000000..bc40e97c111 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded.cs @@ -0,0 +1,672 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a certificate profile. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = value; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded Clone() + { + var clone = new NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded(); + 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._resourceBody = this._resourceBody; + clone.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningCertificateProfile_CreateViaIdentityCodeSigningAccountExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + await this.Client.CertificateProfilesCreateViaIdentity(CodeSigningAccountInputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + await this.Client.CertificateProfilesCreate(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..6bf094b0bec --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded.cs @@ -0,0 +1,659 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a certificate profile. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningCertificateProfile_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningCertificateProfile_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CertificateProfilesCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CertificateProfilesCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..35493c09d59 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath.cs @@ -0,0 +1,621 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a certificate profile. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningCertificateProfile_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath Clone() + { + var clone = new NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath(); + 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.AccountName = this.AccountName; + clone.ProfileName = this.ProfileName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningCertificateProfile_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesCreateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonString.cs new file mode 100644 index 00000000000..82182bf3b23 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/NewAzCodeSigningCertificateProfile_CreateViaJsonString.cs @@ -0,0 +1,617 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// create a certificate profile. + /// + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzCodeSigningCertificateProfile_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"create a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class NewAzCodeSigningCertificateProfile_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzCodeSigningCertificateProfile_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.NewAzCodeSigningCertificateProfile_CreateViaJsonString Clone() + { + var clone = new NewAzCodeSigningCertificateProfile_CreateViaJsonString(); + 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.AccountName = this.AccountName; + clone.ProfileName = this.ProfileName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzCodeSigningCertificateProfile_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesCreateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_Delete.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_Delete.cs new file mode 100644 index 00000000000..a243b1c753e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_Delete.cs @@ -0,0 +1,608 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Delete a trusted signing account. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCodeSigningAccount_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Delete a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class RemoveAzCodeSigningAccount_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCodeSigningAccount_Delete + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.RemoveAzCodeSigningAccount_Delete Clone() + { + var clone = new RemoveAzCodeSigningAccount_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.AccountName = this.AccountName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsDelete(SubscriptionId, ResourceGroupName, AccountName, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzCodeSigningAccount_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_DeleteViaIdentity.cs new file mode 100644 index 00000000000..47a3d2a0102 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningAccount_DeleteViaIdentity.cs @@ -0,0 +1,586 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Delete a trusted signing account. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCodeSigningAccount_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Delete a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class RemoveAzCodeSigningAccount_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCodeSigningAccount_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.RemoveAzCodeSigningAccount_DeleteViaIdentity Clone() + { + var clone = new RemoveAzCodeSigningAccount_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CodeSigningAccountsDeleteViaIdentity(InputObject.Id, onNoContent, 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CodeSigningAccountsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzCodeSigningAccount_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_Delete.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_Delete.cs new file mode 100644 index 00000000000..7bb4c4de106 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_Delete.cs @@ -0,0 +1,623 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Delete a certificate profile. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCodeSigningCertificateProfile_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Delete a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class RemoveAzCodeSigningCertificateProfile_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCodeSigningCertificateProfile_Delete + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.RemoveAzCodeSigningCertificateProfile_Delete Clone() + { + var clone = new RemoveAzCodeSigningCertificateProfile_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.AccountName = this.AccountName; + clone.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesDelete(SubscriptionId, ResourceGroupName, AccountName, ProfileName, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzCodeSigningCertificateProfile_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity.cs new file mode 100644 index 00000000000..c66deb8f49c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity.cs @@ -0,0 +1,590 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Delete a certificate profile. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCodeSigningCertificateProfile_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Delete a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity Clone() + { + var clone = new RemoveAzCodeSigningCertificateProfile_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CertificateProfilesDeleteViaIdentity(InputObject.Id, onNoContent, 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CertificateProfilesDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzCodeSigningCertificateProfile_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount.cs new file mode 100644 index 00000000000..af8409715bb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Delete a certificate profile. + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Delete a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}", ApiVersion = "2024-02-05-preview")] + public partial class RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount Clone() + { + var clone = new RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount(); + 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.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + await this.Client.CertificateProfilesDeleteViaIdentity(CodeSigningAccountInputObject.Id, onNoContent, onOk, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + await this.Client.CertificateProfilesDelete(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzCodeSigningCertificateProfile_DeleteViaIdentityCodeSigningAccount() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_Revoke.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_Revoke.cs new file mode 100644 index 00000000000..08ab31b8b8a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_Revoke.cs @@ -0,0 +1,520 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_Revoke", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_Revoke : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body; + + /// Defines the certificate revocation properties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Defines the certificate revocation properties.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Defines the certificate revocation properties.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate Body { get => this._body; set => this._body = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesRevokeCertificate(SubscriptionId, ResourceGroupName, AccountName, ProfileName, Body, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_Revoke() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeExpanded.cs new file mode 100644 index 00000000000..dfbd3a7b74b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeExpanded.cs @@ -0,0 +1,565 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Defines the certificate revocation properties. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.RevokeCertificate(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// The timestamp when the revocation is effective. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The timestamp when the revocation is effective.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + public global::System.DateTime EffectiveAt { get => _body.EffectiveAt; set => _body.EffectiveAt = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Reason for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Reason for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Reason for the revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + public string Reason { get => _body.Reason ?? null; set => _body.Reason = value; } + + /// Remarks for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Remarks for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + public string Remark { get => _body.Remark ?? null; set => _body.Remark = value; } + + /// 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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Serial number of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Serial number of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Serial number of the certificate.", + SerializedName = @"serialNumber", + PossibleTypes = new [] { typeof(string) })] + public string SerialNumber { get => _body.SerialNumber ?? null; set => _body.SerialNumber = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Thumbprint of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Thumbprint of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Thumbprint of the certificate.", + SerializedName = @"thumbprint", + PossibleTypes = new [] { typeof(string) })] + public string Thumbprint { get => _body.Thumbprint ?? null; set => _body.Thumbprint = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesRevokeCertificate(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _body, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentity.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentity.cs new file mode 100644 index 00000000000..cf1b18c56b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentity.cs @@ -0,0 +1,492 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body; + + /// Defines the certificate revocation properties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Defines the certificate revocation properties.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Defines the certificate revocation properties.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate Body { get => this._body; set => this._body = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CertificateProfilesRevokeCertificateViaIdentity(InputObject.Id, Body, 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CertificateProfilesRevokeCertificate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, Body, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount.cs new file mode 100644 index 00000000000..b9854f62cae --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount.cs @@ -0,0 +1,503 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body; + + /// Defines the certificate revocation properties. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Defines the certificate revocation properties.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Defines the certificate revocation properties.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate Body { get => this._body; set => this._body = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + await this.Client.CertificateProfilesRevokeCertificateViaIdentity(CodeSigningAccountInputObject.Id, Body, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + await this.Client.CertificateProfilesRevokeCertificate(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, Body, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccount() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded.cs new file mode 100644 index 00000000000..303784e0ccf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded.cs @@ -0,0 +1,547 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Defines the certificate revocation properties. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.RevokeCertificate(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// The timestamp when the revocation is effective. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The timestamp when the revocation is effective.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + public global::System.DateTime EffectiveAt { get => _body.EffectiveAt; set => _body.EffectiveAt = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Reason for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Reason for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Reason for the revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + public string Reason { get => _body.Reason ?? null; set => _body.Reason = value; } + + /// Remarks for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Remarks for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + public string Remark { get => _body.Remark ?? null; set => _body.Remark = value; } + + /// Serial number of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Serial number of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Serial number of the certificate.", + SerializedName = @"serialNumber", + PossibleTypes = new [] { typeof(string) })] + public string SerialNumber { get => _body.SerialNumber ?? null; set => _body.SerialNumber = value; } + + /// Thumbprint of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Thumbprint of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Thumbprint of the certificate.", + SerializedName = @"thumbprint", + PossibleTypes = new [] { typeof(string) })] + public string Thumbprint { get => _body.Thumbprint ?? null; set => _body.Thumbprint = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + await this.Client.CertificateProfilesRevokeCertificateViaIdentity(CodeSigningAccountInputObject.Id, _body, onNoContent, onDefault, this, Pipeline); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + await this.Client.CertificateProfilesRevokeCertificate(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, _body, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityCodeSigningAccountExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded.cs new file mode 100644 index 00000000000..d82896b423a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded.cs @@ -0,0 +1,536 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// Defines the certificate revocation properties. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IRevokeCertificate _body = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.RevokeCertificate(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// The timestamp when the revocation is effective. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The timestamp when the revocation is effective.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The timestamp when the revocation is effective.", + SerializedName = @"effectiveAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + public global::System.DateTime EffectiveAt { get => _body.EffectiveAt; set => _body.EffectiveAt = value; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Reason for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Reason for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Reason for the revocation.", + SerializedName = @"reason", + PossibleTypes = new [] { typeof(string) })] + public string Reason { get => _body.Reason ?? null; set => _body.Reason = value; } + + /// Remarks for the revocation. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Remarks for the revocation.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Remarks for the revocation.", + SerializedName = @"remarks", + PossibleTypes = new [] { typeof(string) })] + public string Remark { get => _body.Remark ?? null; set => _body.Remark = value; } + + /// Serial number of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Serial number of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Serial number of the certificate.", + SerializedName = @"serialNumber", + PossibleTypes = new [] { typeof(string) })] + public string SerialNumber { get => _body.SerialNumber ?? null; set => _body.SerialNumber = value; } + + /// Thumbprint of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Thumbprint of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Thumbprint of the certificate.", + SerializedName = @"thumbprint", + PossibleTypes = new [] { typeof(string) })] + public string Thumbprint { get => _body.Thumbprint ?? null; set => _body.Thumbprint = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CertificateProfilesRevokeCertificateViaIdentity(InputObject.Id, _body, 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CertificateProfilesRevokeCertificate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, _body, onNoContent, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaIdentityExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath.cs new file mode 100644 index 00000000000..2f4fad5779b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath.cs @@ -0,0 +1,523 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Revoke operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Revoke operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Revoke operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesRevokeCertificateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _jsonString, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonString.cs new file mode 100644 index 00000000000..bd86eb8c00b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonString.cs @@ -0,0 +1,521 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// Revoke a certificate under a certificate profile. + /// + /// [OpenAPI] RevokeCertificate=>POST:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsSecurity.Revoke, @"AzCodeSigningCertificateProfileCertificate_RevokeViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Revoke a certificate under a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}/revokeCertificate", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Revoke operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Revoke operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Revoke operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesRevokeCertificate' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CertificateProfilesRevokeCertificateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _jsonString, onNoContent, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the + /// cmdlet class. + /// + public RevokeAzCodeSigningCertificateProfileCertificate_RevokeViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 / application/json + if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) + { + WriteObject(true); + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_Check.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_Check.cs new file mode 100644 index 00000000000..2a16479c49f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_Check.cs @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// [OpenAPI] CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzCodeSigningAccountNameAvailability_Check", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Checks that the trusted signing account name is valid and is not already in use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability", ApiVersion = "2024-02-05-preview")] + public partial class TestAzCodeSigningAccountNameAvailability_Check : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability _body; + + /// + /// The parameters used to check the availability of the trusted signing account name. + /// + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The parameters used to check the availability of the trusted signing account name.", ValueFromPipeline = true)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The parameters used to check the availability of the trusted signing account name.", + SerializedName = @"body", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability Body { get => this._body; set => this._body = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCheckNameAvailability(SubscriptionId, Body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzCodeSigningAccountNameAvailability_Check() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// 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.CodeSigning.Models.ICheckNameAvailabilityResult + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckExpanded.cs new file mode 100644 index 00000000000..f08e72ffd4f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckExpanded.cs @@ -0,0 +1,495 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// [OpenAPI] CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzCodeSigningAccountNameAvailability_CheckExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Checks that the trusted signing account name is valid and is not already in use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability", ApiVersion = "2024-02-05-preview")] + public partial class TestAzCodeSigningAccountNameAvailability_CheckExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The parameters used to check the availability of the trusted signing account name. + /// + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailability _body = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CheckNameAvailability(); + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Trusted signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted signing account name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted signing account name.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + public string Name { get => _body.Name ?? null; set => _body.Name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCheckNameAvailability(SubscriptionId, _body, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzCodeSigningAccountNameAvailability_CheckExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// 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.CodeSigning.Models.ICheckNameAvailabilityResult + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonFilePath.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonFilePath.cs new file mode 100644 index 00000000000..3847b4483b4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonFilePath.cs @@ -0,0 +1,496 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// [OpenAPI] CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzCodeSigningAccountNameAvailability_CheckViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Checks that the trusted signing account name is valid and is not already in use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class TestAzCodeSigningAccountNameAvailability_CheckViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Check operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Check operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Check operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCheckNameAvailabilityViaJsonString(SubscriptionId, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public TestAzCodeSigningAccountNameAvailability_CheckViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// 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.CodeSigning.Models.ICheckNameAvailabilityResult + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonString.cs new file mode 100644 index 00000000000..e8f36fb085c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/TestAzCodeSigningAccountNameAvailability_CheckViaJsonString.cs @@ -0,0 +1,493 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// + /// Checks that the trusted signing account name is valid and is not already in use. + /// + /// + /// [OpenAPI] CheckNameAvailability=>POST:"/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsDiagnostic.Test, @"AzCodeSigningAccountNameAvailability_CheckViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"Checks that the trusted signing account name is valid and is not already in use.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Microsoft.CodeSigning/checkNameAvailability", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class TestAzCodeSigningAccountNameAvailability_CheckViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Check operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Check operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Check operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsCheckNameAvailability' operation")) + { + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsCheckNameAvailabilityViaJsonString(SubscriptionId, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public TestAzCodeSigningAccountNameAvailability_CheckViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICheckNameAvailabilityResult + /// 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.CodeSigning.Models.ICheckNameAvailabilityResult + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateExpanded.cs new file mode 100644 index 00000000000..bd6f0662d4d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateExpanded.cs @@ -0,0 +1,615 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a trusted signing account. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningAccount_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class UpdateAzCodeSigningAccount_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Parameters for creating or updating a trusted signing account. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatch(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + public string SkuName { get => _propertiesBody.SkuName ?? null; set => _propertiesBody.SkuName = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => _propertiesBody.Tag ?? null /* object */; set => _propertiesBody.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzCodeSigningAccount_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningAccount_UpdateExpanded Clone() + { + var clone = new UpdateAzCodeSigningAccount_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._propertiesBody = this._propertiesBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.AccountName = this.AccountName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsUpdate(SubscriptionId, ResourceGroupName, AccountName, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningAccount_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..b1fec252d87 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded.cs @@ -0,0 +1,593 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a trusted signing account. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningAccount_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + public partial class UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Parameters for creating or updating a trusted signing account. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccountPatch _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CodeSigningAccountPatch(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Name of the SKU. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Name of the SKU.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Name of the SKU.", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("Basic", "Premium")] + public string SkuName { get => _propertiesBody.SkuName ?? null; set => _propertiesBody.SkuName = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ITags Tag { get => _propertiesBody.Tag ?? null /* object */; set => _propertiesBody.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._propertiesBody = this._propertiesBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.CodeSigningAccountsUpdateViaIdentity(InputObject.Id, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.CodeSigningAccountsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningAccount_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..19246f2509a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonFilePath.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a trusted signing account. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningAccount_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class UpdateAzCodeSigningAccount_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzCodeSigningAccount_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningAccount_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzCodeSigningAccount_UpdateViaJsonFilePath(); + 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.AccountName = this.AccountName; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsUpdateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningAccount_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonString.cs new file mode 100644 index 00000000000..d624fd47fb5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningAccount_UpdateViaJsonString.cs @@ -0,0 +1,602 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a trusted signing account. + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningAccount_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a trusted signing account.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}", ApiVersion = "2024-02-05-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.NotSuggestDefaultParameterSet] + public partial class UpdateAzCodeSigningAccount_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzCodeSigningAccount_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningAccount_UpdateViaJsonString Clone() + { + var clone = new UpdateAzCodeSigningAccount_UpdateViaJsonString(); + 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.AccountName = this.AccountName; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CodeSigningAccountsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.CodeSigningAccountsUpdateViaJsonString(SubscriptionId, ResourceGroupName, AccountName, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningAccount_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningAccount + /// 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.CodeSigning.Models.ICodeSigningAccount + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateExpanded.cs new file mode 100644 index 00000000000..95af72d6986 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateExpanded.cs @@ -0,0 +1,724 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningCertificateProfile_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + public partial class UpdateAzCodeSigningCertificateProfile_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Backing field for property. + private string _accountName; + + /// Trusted Signing account name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Trusted Signing account name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Trusted Signing account name.", + SerializedName = @"accountName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string AccountName { get => this._accountName; set => this._accountName = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = value; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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 Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzCodeSigningCertificateProfile_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningCertificateProfile_UpdateExpanded Clone() + { + var clone = new UpdateAzCodeSigningCertificateProfile_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.AccountName = this.AccountName; + clone.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.CertificateProfilesGetWithResult(SubscriptionId, ResourceGroupName, AccountName, ProfileName, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CertificateProfilesCreate(SubscriptionId, ResourceGroupName, AccountName, ProfileName, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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,AccountName=AccountName,ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningCertificateProfile_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ProfileType"))) + { + this.ProfileType = (string)(this.MyInvocation?.BoundParameters["ProfileType"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeStreetAddress"))) + { + this.IncludeStreetAddress = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeStreetAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCity"))) + { + this.IncludeCity = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCity"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeState"))) + { + this.IncludeState = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeState"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCountry"))) + { + this.IncludeCountry = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCountry"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludePostalCode"))) + { + this.IncludePostalCode = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludePostalCode"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IdentityValidationId"))) + { + this.IdentityValidationId = (string)(this.MyInvocation?.BoundParameters["IdentityValidationId"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded.cs new file mode 100644 index 00000000000..6abdfb4b726 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded.cs @@ -0,0 +1,708 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + public partial class UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _codeSigningAccountInputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity CodeSigningAccountInputObject { get => this._codeSigningAccountInputObject; set => this._codeSigningAccountInputObject = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Backing field for property. + private string _profileName; + + /// Certificate profile name. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Certificate profile name.")] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Certificate profile name.", + SerializedName = @"profileName", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public string ProfileName { get => this._profileName; set => this._profileName = value; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded Clone() + { + var clone = new UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded(); + 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._resourceBody = this._resourceBody; + clone.ProfileName = this.ProfileName; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (CodeSigningAccountInputObject?.Id != null) + { + this.CodeSigningAccountInputObject.Id += $"/certificateProfiles/{(global::System.Uri.EscapeDataString(this.ProfileName.ToString()))}"; + _resourceBody = await this.Client.CertificateProfilesGetViaIdentityWithResult(CodeSigningAccountInputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CertificateProfilesCreateViaIdentity(CodeSigningAccountInputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + else + { + // try to call with PATH parameters from Input Object + if (null == CodeSigningAccountInputObject.SubscriptionId) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.ResourceGroupName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + if (null == CodeSigningAccountInputObject.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("CodeSigningAccountInputObject has null value for CodeSigningAccountInputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, CodeSigningAccountInputObject) ); + } + _resourceBody = await this.Client.CertificateProfilesGetWithResult(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CertificateProfilesCreate(CodeSigningAccountInputObject.SubscriptionId ?? null, CodeSigningAccountInputObject.ResourceGroupName ?? null, CodeSigningAccountInputObject.AccountName ?? null, ProfileName, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.UndeclaredResponseException urexception) + { + WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ProfileName=ProfileName}) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } + }); + } + finally + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityCodeSigningAccountExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ProfileType"))) + { + this.ProfileType = (string)(this.MyInvocation?.BoundParameters["ProfileType"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeStreetAddress"))) + { + this.IncludeStreetAddress = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeStreetAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCity"))) + { + this.IncludeCity = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCity"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeState"))) + { + this.IncludeState = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeState"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCountry"))) + { + this.IncludeCountry = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCountry"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludePostalCode"))) + { + this.IncludePostalCode = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludePostalCode"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IdentityValidationId"))) + { + this.IdentityValidationId = (string)(this.MyInvocation?.BoundParameters["IdentityValidationId"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..9069c2a2c44 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/cmdlets/UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded.cs @@ -0,0 +1,696 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets; + using System; + + /// update a certificate profile. + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// [OpenAPI] Create=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CodeSigning/codeSigningAccounts/{accountName}/certificateProfiles/{profileName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzCodeSigningCertificateProfile_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile))] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Description(@"update a certificate profile.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Generated] + public partial class UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Certificate profile resource. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.CertificateProfile(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Identity validation id used for the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Identity validation id used for the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Identity validation id used for the certificate subject name.", + SerializedName = @"identityValidationId", + PossibleTypes = new [] { typeof(string) })] + public string IdentityValidationId { get => _resourceBody.IdentityValidationId ?? null; set => _resourceBody.IdentityValidationId = value; } + + /// + /// Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include L in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCity", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCity { get => _resourceBody.IncludeCity ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCity = value; } + + /// + /// Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include C in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeCountry", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeCountry { get => _resourceBody.IncludeCountry ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeCountry = value; } + + /// Whether to include PC in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include PC in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include PC in the certificate subject name.", + SerializedName = @"includePostalCode", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludePostalCode { get => _resourceBody.IncludePostalCode ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludePostalCode = value; } + + /// + /// Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include S in the certificate subject name. Applicable only for private trust, private trust ci profile types", + SerializedName = @"includeState", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeState { get => _resourceBody.IncludeState ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeState = value; } + + /// Whether to include STREET in the certificate subject name. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Whether to include STREET in the certificate subject name.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Whether to include STREET in the certificate subject name.", + SerializedName = @"includeStreetAddress", + PossibleTypes = new [] { typeof(global::System.Management.Automation.SwitchParameter) })] + public global::System.Management.Automation.SwitchParameter IncludeStreetAddress { get => _resourceBody.IncludeStreetAddress ?? default(global::System.Management.Automation.SwitchParameter); set => _resourceBody.IncludeStreetAddress = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICodeSigningIdentity 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.CodeSigning.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.HttpPipeline Pipeline { get; set; } + + /// Profile type of the certificate. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Profile type of the certificate.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Profile type of the certificate.", + SerializedName = @"profileType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.PSArgumentCompleterAttribute("PublicTrust", "PrivateTrust", "PrivateTrustCIPolicy", "VBSEnclave", "PublicTrustTest")] + public string ProfileType { get => _resourceBody.ProfileType ?? null; set => _resourceBody.ProfileType = 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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Category(global::Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Cmdlets.UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.CodeSigning.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'CertificateProfilesCreate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.CertificateProfilesGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CertificateProfilesCreateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + 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.AccountName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.AccountName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + if (null == InputObject.ProfileName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ProfileName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.CertificateProfilesGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, this, Pipeline); + this.Update_resourceBody(); + await this.Client.CertificateProfilesCreate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.AccountName ?? null, InputObject.ProfileName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet + /// class. + /// + public UpdateAzCodeSigningCertificateProfile_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ProfileType"))) + { + this.ProfileType = (string)(this.MyInvocation?.BoundParameters["ProfileType"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeStreetAddress"))) + { + this.IncludeStreetAddress = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeStreetAddress"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCity"))) + { + this.IncludeCity = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCity"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeState"))) + { + this.IncludeState = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeState"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludeCountry"))) + { + this.IncludeCountry = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludeCountry"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IncludePostalCode"))) + { + this.IncludePostalCode = (global::System.Management.Automation.SwitchParameter)(this.MyInvocation?.BoundParameters["IncludePostalCode"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("IdentityValidationId"))) + { + this.IdentityValidationId = (string)(this.MyInvocation?.BoundParameters["IdentityValidationId"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Models.ICertificateProfile + /// 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.CodeSigning.Models.ICertificateProfile + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..0dbfc34f8a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this cmdlet"); + } + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..f0855475595 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..a501b3458e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to a type + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..292b3f4f596 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..43fe35a24bf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..48b0282138c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..7b58b986591 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..bf0940ec66b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..9ea5b1cbf48 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..bd76a4b4bc1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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.CodeSigning.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..11037706a67 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.HasAllowEmptyArray.ToAllowEmptyArray()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..1878ee0a74e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.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.CodeSigning.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: CodeSigning cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.CodeSigning.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.CodeSigning.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = '{previewVersion}'"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule Sphere".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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..3c89399cbdf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + /*var loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + + + + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + sb.AppendLine(@"{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath)" + ); + sb.AppendLine($@" $TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@" $currentPath = $PSScriptRoot + while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent + } + . ($mockingPath | Select-Object -First 1).FullName +} +"); + + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..22feb261b1c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..c165ec3c64c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..2c86ef0e9af --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..a67e893fad3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..9c21ff1ba84 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"[{relatedLink}]({relatedLink}){Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..b4697fa33b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..be61fd74309 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + ExampleInfo.Description.ToDescriptionFormat()); ; + } + } + } + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://learn.microsoft.com/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Synopsis.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + public const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..71d31fc6d45 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..7285331ab12 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && !pg.Parameters.All(p => p.IsHidden())) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (codeEndIndex ?? 0)) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, output, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow && !p.IsHidden()).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..8d75911cd29 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{Environment.NewLine}" : String.Empty; + } + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText}{externalUrlsText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new[] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new[] { "
", "\r\n", "\n" }); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..19d76313d16 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + + public string RootModuleName { get => @""; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + if (variantParamCountGroups.Length == 0) + { + variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + } + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public bool IsNotSuggestDefaultParameterSet { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + IsNotSuggestDefaultParameterSet = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public bool HasAllowEmptyArray { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + public PSArgumentCompleterAttribute PSArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}"; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines(); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[] { } : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => (!ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + public static PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(completerAttribute); + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..f6391344804 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class ConstantAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..a6d3ab258b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..61c1a017da9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,105 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.TrimStart().StartsWith(GuidStart.TrimStart()))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..2ddaff207d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..3b5874dff33 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..b2c65b0736c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..2bb02dcf8fb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.CodeSigningManagementClient Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..77bd73c62a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..d7b3acef4a0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..3352b385b8b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..d91cbbb8405 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..c53de72b968 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..c7590336a1a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..5b566812f52 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..b78d4691576 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..ccea9f02c6d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..07a51e9131e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..85c96602e97 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..e4b070fc7f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..9466795e097 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..70b70285581 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..81ea649f4c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..a4b2a08fce7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..8408ba0e21e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..b1d4b4932d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..8061498edcd --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..6b0f804e52d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..7f2c53a308e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..0044101dcd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..5fdfa539704 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..87b41797f47 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..2e862dd7a3e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..73eda881050 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..26c92059249 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..110274e5ecc --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.JsonSerializable.ToJson(dict, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..cdb6f68e3ff --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..df9dfb126ea --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..37a5c194baf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..216a48bed5d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..a1f0c046bcf --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..35aedb5319b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..3aa152a7927 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..4336f9beffb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..9ea1428be53 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..5e9011ca367 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..7d2a66a3a61 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime +{ + using System; + + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..ead1a2af252 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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.CodeSigning.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..f9bcf1dd2fd --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + public const string Progress = nameof(Progress); + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..5baabf88e52 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..e0c47dccba2 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Extensions.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..209bcc7faed --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..742176afb69 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..79db47de474 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..ed7f25b66fe --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..03df797c86c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..8060f808ef0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..6c89203b7cb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..1b01c0a62a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..507d5b7fe76 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..4660cdb5e83 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/ISendAsync.cs @@ -0,0 +1,413 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private const int DefaultMaxRetry = 3; + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..d519ef7f2af --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..6f4ec293694 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..0f3c57f08bd --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..5f0d4e8beca --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..fe4c1321d15 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..9eda08ede4e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..2513739c818 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..8de6c883def --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..b07be8ff14f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..55c95f7d7be --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..d70a4736c78 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..a21bc4f02e3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..d62cd77056d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..6502111f77e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + internal XNodeArray(System.Collections.Generic.List values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..7c4b90a8065 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..bd989fffb33 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..358d5f66d95 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..90f7bcf0887 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..32193b26c48 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..dd9541ba91e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..a32d638cf92 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..fb3439145dc --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..41aa3fb725f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..582b3e9ccce --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..7afa160fdd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..8f24a4356f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..6f3f4c9b141 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..6b799ce7f4b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..97b1f22ca49 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..b06d382ab12 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..7cd7a1dfb2c --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"), isBase64Request)) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..30cb39b73aa --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..a08a2e50172 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..af0bb4b8ad2 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..9a7def4e51a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..94cc8d70027 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..a2c2f8d6ae1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..b81e7ba44b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/SerializationMode.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..dca03950fbb --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.List SelectToList(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }.ToList(); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0].ToList(); // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result; + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..59d711be74b --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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.CodeSigning.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // see if there is an error block in the body + json = json?.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..9e2e3d58683 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/CodeSigning.Management/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..7b7f30bc4c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/how-to.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/how-to.md new file mode 100644 index 00000000000..70b1f7c4fc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.CodeSigning`. + +## Building `Az.CodeSigning` +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.CodeSigning` +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.CodeSigning` +To pack `Az.CodeSigning` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.CodeSigning`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.CodeSigning.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.CodeSigning.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.CodeSigning`. + - `-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.CodeSigning` 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/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/Az.CodeSigning.internal.psm1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/Az.CodeSigning.internal.psm1 new file mode 100644 index 00000000000..f2b3fb71f68 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/Az.CodeSigning.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.CodeSigning.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/README.md new file mode 100644 index 00000000000..6fc386a0b35 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/internal/README.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.CodeSigning.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.CodeSigning`. Instead, this sub-module is imported by the `..\custom\Az.CodeSigning.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.CodeSigning.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.CodeSigning`. diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/license.txt b/tests-upgrade/tests-emitter/CodeSigning.Management/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/license.txt @@ -0,0 +1,227 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + + +The software includes the AutoMapper library ("AutoMapper"). The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Provided for Informational Purposes Only + +AutoMapper + +The MIT License (MIT) +Copyright (c) 2010 Jimmy Bogard + + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + +*************** + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/pack-module.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/resources/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/run-module.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/run-module.ps1 new file mode 100644 index 00000000000..fc65ba54427 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CodeSigning.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/tests-upgrade/tests-emitter/CodeSigning.Management/target/test-module.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/test-module.ps1 new file mode 100644 index 00000000000..f4cac12b288 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) +{ + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.CodeSigning.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/test/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/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/tests-upgrade/tests-emitter/CodeSigning.Management/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/README.md new file mode 100644 index 00000000000..cdaf3a995a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/README.md @@ -0,0 +1,438 @@ + +# Az.Resources.TestSupport +This directory contains the PowerShell module for the Resources service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Resources.TestSupport`, 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
`npm install -g 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` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +> Values +``` yaml +azure: true +powershell: true +branch: master +repo: https://github.com/Azure/azure-rest-api-specs/blob/$(branch) +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + copyright: Microsoft Corporation. All rights reserved. + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell +``` + +> Names +``` yaml +prefix: Az +``` + +> Folders +``` yaml +clear-output-folder: true +``` + +``` yaml +input-file: + - $(repo)/specification/resources/resource-manager/Microsoft.Resources/stable/2018-05-01/resources.json +module-name: Az.Resources.TestSupport +namespace: Microsoft.Azure.PowerShell.Cmdlets.Resources + +subject-prefix: '' +module-version: 0.0.1 +title: Resources + +directive: + - remove-operation: Deployments_CreateOrUpdateAtSubscriptionScope + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - from: swagger-document + where: $..parameters[?(@.name=='$filter')] + transform: $['x-ms-skip-url-encoding'] = true + - from: swagger-document + where: $..[?( /Resources_(CreateOrUpdate|Update|Delete|Get|GetById|CheckExistence|CheckExistenceById)/g.exec(@.operationId))] + transform: "$.parameters = $.parameters.map( each => { each.name = each.name === 'api-version' ? 'explicit-api-version' : each.name; return each; } );" + - from: source-file-csharp + where: $ + transform: $ = $.replace(/explicit-api-version/g, 'api-version'); + - where: + parameter-name: ExplicitApiVersion + set: + parameter-name: ApiVersion + - from: source-file-csharp + where: $ + transform: > + $ = $.replace(/result.OdataNextLink/g,'nextLink' ); + return $.replace( /(^\s*)(if\s*\(\s*nextLink\s*!=\s*null\s*\))/gm, '$1var nextLink = Module.Instance.FixNextLink(responseMessage, result.OdataNextLink);\n$1$2' ); + - from: swagger-document + where: + - $..DeploymentProperties.properties.template + - $..DeploymentProperties.properties.parameters + - $..ResourceGroupExportResult.properties.template + - $..PolicyDefinitionProperties.properties.policyRule + transform: $.additionalProperties = true; + - where: + verb: Set + subject: Resource + remove: true + - where: + verb: Set + subject: Deployment + remove: true + - where: + subject: Resource + parameter-name: GroupName + set: + parameter-name: ResourceGroupName + clear-alias: true + - where: + subject: Resource + parameter-name: Id + set: + parameter-name: ResourceId + clear-alias: true + - where: + subject: Resource + parameter-name: Type + set: + parameter-name: ResourceType + clear-alias: true + - where: + subject: Appliance* + remove: true + - where: + verb: Test + subject: CheckNameAvailability + set: + subject: NameAvailability + - where: + verb: Export + subject: ResourceGroupTemplate + set: + subject: ResourceGroup + alias: Export-AzResourceGroupTemplate + - where: + parameter-name: Filter + set: + alias: ODataQuery + - where: + verb: Test + subject: ResourceGroupExistence + set: + subject: ResourceGroup + alias: Test-AzResourceGroupExistence + - where: + verb: Export + subject: DeploymentTemplate + set: + alias: [Save-AzDeploymentTemplate, Save-AzResourceGroupDeploymentTemplate] + - where: + subject: Deployment + set: + alias: ${verb}-AzResourceGroupDeployment + - where: + verb: Get + subject: DeploymentOperation + set: + alias: Get-AzResourceGroupDeploymentOperation + - where: + verb: New + subject: Deployment + variant: Create.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + hide: true + - where: + verb: Test + subject: Deployment + variant: Validate.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + parameter-name: DebugSettingDetailLevel + set: + parameter-name: DeploymentDebugLogLevel + - where: + subject: Provider + set: + subject: ResourceProvider + - where: + subject: ProviderFeature|ResourceProvider|ResourceLock + parameter-name: ResourceProviderNamespace + set: + alias: ProviderNamespace + - where: + verb: Update + subject: ResourceGroup + parameter-name: Name + clear-alias: true + - where: + parameter-name: UpnOrObjectId + set: + alias: ['UserPrincipalName', 'Upn', 'ObjectId'] + - where: + subject: Deployment + variant: (.*)Expanded(.*) + parameter-name: Parameter + set: + parameter-name: DeploymentParameter + # Format output + - where: + model-name: GenericResource + set: + format-table: + properties: + - Name + - ResourceGroupName + - Type + - Location + labels: + Type: ResourceType + - where: + model-name: ResourceGroup + set: + format-table: + properties: + - Name + - Location + - ProvisioningState + - where: + model-name: DeploymentExtended + set: + format-table: + properties: + - Name + - ProvisioningState + - Timestamp + - Mode + - where: + model-name: PolicyAssignment + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicyDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicySetDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: Provider + set: + format-table: + properties: + - Namespace + - RegistrationState + - where: + model-name: ProviderResourceType + set: + format-table: + properties: + - ResourceType + - Location + - ApiVersion + - where: + model-name: FeatureResult + set: + format-table: + properties: + - Name + - State + - where: + model-name: TagDetails + set: + format-table: + properties: + - TagName + - CountValue + - where: + model-name: Application + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppId + - Homepage + - AvailableToOtherTenant + - where: + model-name: KeyCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - Type + - where: + model-name: PasswordCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - where: + model-name: User + set: + format-table: + properties: + - PrincipalName + - DisplayName + - ObjectId + - Type + - where: + model-name: AdGroup + set: + format-table: + properties: + - DisplayName + - Mail + - ObjectId + - SecurityEnabled + - where: + model-name: ServicePrincipal + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppDisplayName + - AppId + - where: + model-name: Location + set: + format-table: + properties: + - Name + - DisplayName + - where: + model-name: ManagementLockObject + set: + format-table: + properties: + - Name + - Level + - ResourceId + - where: + model-name: RoleAssignment + set: + format-table: + properties: + - DisplayName + - ObjectId + - ObjectType + - RoleDefinitionName + - Scope + - where: + model-name: RoleDefinition + set: + format-table: + properties: + - RoleName + - Name + - Action +# To remove cmdlets not used in the test frame + - where: + subject: Operation + remove: true + - where: + subject: Deployment + variant: (.*)1|Cancel(.*)|Validate(.*)|Export(.*)|List(.*)|Delete(.*)|Check(.*)|Calculate(.*) + remove: true + - where: + subject: ResourceProvider + variant: Register(.*)|Unregister(.*)|Get(.*) + remove: true + - where: + subject: ResourceGroup + variant: List(.*)|Update(.*)|Export(.*)|Move(.*) + remove: true + - where: + subject: Resource + remove: true + - where: + subject: Tag|TagValue + remove: true + - where: + subject: DeploymentOperation + remove: true + - where: + subject: DeploymentTemplate + remove: true + - where: + subject: Calculate(.*) + remove: true + - where: + subject: ResourceExistence + remove: true + - where: + subject: ResourceMoveResource + remove: true + - where: + subject: DeploymentExistence + remove: true +``` diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/custom/New-AzDeployment.ps1 @@ -0,0 +1,231 @@ +function New-AzDeployment { + [OutputType('Microsoft.Azure.PowerShell.Cmdlets.Resources.Models.IDeploymentExtended')] + [CmdletBinding(DefaultParameterSetName='CreateWithTemplateFileParameterFile', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Description('You can provide the template and parameters directly in the request or link to JSON files.')] + param( + [Parameter(HelpMessage='The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name.')] + [Alias('DeploymentName')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='deploymentName', Required, PossibleTypes=([System.String]), Description='The name of the deployment.')] + [System.String] + # The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name. + ${Name}, + + [Parameter(Mandatory, HelpMessage='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='subscriptionId', Required, PossibleTypes=([System.String]), Description='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='resourceGroupName', Required, PossibleTypes=([System.String]), Description='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [System.String] + # The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [System.String] + # Local path to the JSON template file. + ${TemplateFile}, + + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [System.String] + # The string representation of the JSON template. + ${TemplateJson}, + + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the JSON template. + ${TemplateObject}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [System.String] + # Local path to the parameter JSON template file. + ${TemplateParameterFile}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [System.String] + # The string representation of the parameter JSON template. + ${TemplateParameterJson}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the parameter JSON template. + ${TemplateParameterObject}, + + [Parameter(Mandatory, HelpMessage='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode])] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='mode', Required, PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode]), Description='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode] + # The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. + ${Mode}, + + [Parameter(HelpMessage='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='detailLevel', PossibleTypes=([System.String]), Description='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [System.String] + # Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations. + ${DeploymentDebugLogLevel}, + + [Parameter(HelpMessage='The location to store the deployment data.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='location', PossibleTypes=([System.String]), Description='The location to store the deployment data.')] + [System.String] + # The location to store the deployment data. + ${Location}, + + [Parameter(HelpMessage='The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(HelpMessage='Run the command asynchronously')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait} + + ) + + process { + if ($PSBoundParameters.ContainsKey("TemplateFile")) + { + if (!(Test-Path -Path $TemplateFile)) + { + throw "Unable to find template file '$TemplateFile'." + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (Get-Item -Path $TemplateFile).BaseName + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + $TemplateJson = [System.IO.File]::ReadAllText($TemplateFile) + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateJson")) + { + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateObject")) + { + $TemplateJson = ConvertTo-Json -InputObject $TemplateObject + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateObject") + } + + if ($PSBoundParameters.ContainsKey("TemplateParameterFile")) + { + if (!(Test-Path -Path $TemplateParameterFile)) + { + throw "Unable to find template parameter file '$TemplateParameterFile'." + } + + $ParameterJson = [System.IO.File]::ReadAllText($TemplateParameterFile) + $ParameterObject = ConvertFrom-Json -InputObject $ParameterJson + $ParameterHashtable = @{} + $ParameterObject.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + $ParameterHashtable.Remove("`$schema") + $ParameterHashtable.Remove("contentVersion") + $NestedValues = $ParameterHashtable.parameters + if ($null -ne $NestedValues) + { + $ParameterHashtable.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + } + + $ParameterJson = ConvertTo-Json -InputObject $ParameterHashtable + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $ParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterJson")) + { + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterObject")) + { + $TemplateParameterObject.Remove("`$schema") + $TemplateParameterObject.Remove("contentVersion") + $NestedValues = $TemplateParameterObject.parameters + if ($null -ne $NestedValues) + { + $TemplateParameterObject.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $TemplateParameterObject[$_.Name] = $_.Value } + } + + $TemplateParameterJson = ConvertTo-Json -InputObject $TemplateParameterObject + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterObject") + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (New-Guid).Guid + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + if ($PSBoundParameters.ContainsKey("ResourceGroupName")) + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + else + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Resources` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overriden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Resources` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/how-to.md @@ -0,0 +1,60 @@ +# How-To +This document describes how to develop for `Az.Resources`. + +## Building `Az.Resources` +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.Resources` +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.Resources` +To pack `Az.Resources` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Resources`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Resources.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Resources.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Resources`. + - `-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.Resources` 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`. +- `generate-portal-ux.ps1` + - Generates a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +- `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/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/license.txt @@ -0,0 +1,203 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md @@ -0,0 +1,598 @@ +### AzADApplication [Get, New, Remove, Update] `IApplication, Boolean` + - TenantId `String` + - ObjectId `String` + - IncludeDeleted `SwitchParameter` + - InputObject `IResourcesIdentity` + - HardDelete `SwitchParameter` + - Filter `String` + - IdentifierUri `String` + - DisplayNameStartWith `String` + - DisplayName `String` + - ApplicationId `String` + - AllowGuestsSignIn `SwitchParameter` + - AllowPassthroughUser `SwitchParameter` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenants `SwitchParameter` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes` + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `SwitchParameter` + - Oauth2AllowUrlPathMatching `SwitchParameter` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `SwitchParameter` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `SwitchParameter` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + - Parameter `IApplicationCreateParameters` + - PassThru `SwitchParameter` + - AvailableToOtherTenant `SwitchParameter` + +### AzADApplicationOwner [Add, Get, Remove] `Boolean, IDirectoryObject` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADDeletedApplication [Restore] `IApplication` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + +### AzADGroup [Get, New, Remove] `IAdGroup, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayNameStartsWith `String` + - DisplayName `String` + - AdditionalProperties `Hashtable` + - MailNickname `String` + - Parameter `IGroupCreateParameters` + - PassThru `SwitchParameter` + +### AzADGroupMember [Add, Get, Remove, Test] `Boolean, IDirectoryObject, SwitchParameter` + - GroupObjectId `String` + - TenantId `String` + - MemberObjectId `String[]` + - MemberUserPrincipalName `String[]` + - GroupObject `IAdGroup` + - GroupDisplayName `String` + - InputObject `IResourcesIdentity` + - ObjectId `String` + - ShowOwner `SwitchParameter` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IGroupAddMemberParameters` + - DisplayName `String` + - GroupId `String` + - MemberId `String` + +### AzADGroupMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IGroupGetMemberGroupsParameters` + +### AzADGroupOwner [Add, Remove] `Boolean` + - ObjectId `String` + - TenantId `String` + - GroupObjectId `String` + - MemberObjectId `String[]` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADObject [Get] `IDirectoryObject` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - IncludeDirectoryObjectReference `SwitchParameter` + - ObjectId `String[]` + - Type `String[]` + - Parameter `IGetObjectsParameters` + +### AzADServicePrincipal [Get, New, Remove, Update] `IServicePrincipal, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ApplicationObject `IApplication` + - ServicePrincipalName `String` + - DisplayNameBeginsWith `String` + - DisplayName `String` + - ApplicationId `String` + - AccountEnabled `SwitchParameter` + - AppId `String` + - AppRoleAssignmentRequired `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + - Parameter `IServicePrincipalCreateParameters` + - PassThru `SwitchParameter` + +### AzADServicePrincipalOwner [Get] `IDirectoryObject` + - ObjectId `String` + - TenantId `String` + +### AzADUser [Get, New, Remove, Update] `IUser, Boolean` + - TenantId `String` + - UpnOrObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayName `String` + - StartsWith `String` + - Mail `String` + - MailNickname `String` + - Parameter `IUserCreateParameters` + - AccountEnabled `SwitchParameter` + - GivenName `String` + - ImmutableId `String` + - PasswordProfile `IPasswordProfile` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType` + - PassThru `SwitchParameter` + - EnableAccount `SwitchParameter` + +### AzADUserMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IUserGetMemberGroupsParameters` + +### AzApplicationKeyCredentials [Get, Update] `IKeyCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IKeyCredentialsUpdateParameters` + - Value `IKeyCredential[]` + +### AzApplicationPasswordCredentials [Get, Update] `IPasswordCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IPasswordCredentialsUpdateParameters` + - Value `IPasswordCredential[]` + +### AzAuthorizationOperation [Get] `IOperation` + +### AzClassicAdministrator [Get] `IClassicAdministrator` + - SubscriptionId `String[]` + +### AzDenyAssignment [Get] `IDenyAssignment` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - Filter `String` + +### AzDeployment [Get, New, Remove, Set, Stop, Test] `IDeploymentExtended, Boolean, IDeploymentValidateResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Top `Int32` + - Parameter `IDeployment` + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - PassThru `SwitchParameter` + +### AzDeploymentExistence [Test] `Boolean` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDeploymentOperation [Get] `IDeploymentOperation` + - DeploymentName `String` + - SubscriptionId `String[]` + - ResourceGroupName `String` + - OperationId `String` + - DeploymentObject `IDeploymentExtended` + - InputObject `IResourcesIdentity` + - Top `Int32` + +### AzDeploymentTemplate [Export] `IDeploymentExportResultTemplate` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDomain [Get] `IDomain` + - TenantId `String` + - Name `String` + - InputObject `IResourcesIdentity` + - Filter `String` + +### AzElevateGlobalAdministratorAccess [Invoke] `Boolean` + +### AzEntity [Get] `IEntityInfo` + - Filter `String` + - GroupName `String` + - Search `String` + - Select `String` + - Skip `Int32` + - Skiptoken `String` + - Top `Int32` + - View `String` + - CacheControl `String` + +### AzManagedApplication [Get, New, Remove, Set, Update] `IApplication, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplication` + - ApplicationDefinitionId `String` + - IdentityType `ResourceIdentityType` + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagedApplicationDefinition [Get, New, Remove, Set] `IApplicationDefinition, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplicationDefinition` + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - PackageFileUri `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagementGroup [Get, New, Remove, Set, Update] `IManagementGroup, IManagementGroupInfo, Boolean` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Expand `String` + - Filter `String` + - Recurse `SwitchParameter` + - CacheControl `String` + - DisplayName `String` + - Name `String` + - ParentId `String` + - CreateManagementGroupRequest `ICreateManagementGroupRequest` + - PatchGroupRequest `IPatchManagementGroupRequest` + +### AzManagementGroupDescendant [Get] `IDescendantInfo` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Top `Int32` + +### AzManagementGroupSubscription [New, Remove] `Boolean` + - GroupId `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - CacheControl `String` + +### AzManagementLock [Get, New, Remove, Set] `IManagementLockObject, Boolean` + - SubscriptionId `String[]` + - LockName `String` + - ResourceGroupName `String` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Level `LockLevel` + - Note `String` + - Owner `IManagementLockOwner[]` + - Parameter `IManagementLockObject` + +### AzNameAvailability [Test] `ICheckNameAvailabilityResult` + - Name `String` + - Type `Type` + - CheckNameAvailabilityRequest `ICheckNameAvailabilityRequest` + +### AzOAuth2PermissionGrant [Get, New, Remove] `IOAuth2PermissionGrant, Boolean` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ClientId `String` + - ConsentType `ConsentType` + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + - Body `IOAuth2PermissionGrant` + +### AzPermission [Get] `IPermission` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + +### AzPolicyAssignment [Get, New, Remove] `IPolicyAssignment` + - Id `String` + - Name `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - PolicyDefinitionId `String` + - IncludeDescendent `SwitchParameter` + - Filter `String` + - Parameter `IPolicyAssignment` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - SkuName `String` + - SkuTier `String` + - PropertiesScope `String` + +### AzPolicyDefinition [Get, New, Remove, Set] `IPolicyDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicyDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzPolicySetDefinition [Get, New, Remove, Set] `IPolicySetDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicySetDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzProviderFeature [Get, Register] `IFeatureResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + +### AzProviderOperationsMetadata [Get] `IProviderOperationsMetadata` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + +### AzResource [Get, Move, New, Remove, Set, Test, Update] `IGenericResource, Boolean` + - ResourceId `String` + - Name `String` + - ParentResourcePath `String` + - ProviderNamespace `String` + - ResourceGroupName `String` + - ResourceType `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - SourceResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - Expand `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Filter `String` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + - IdentityType `ResourceIdentityType` + - IdentityUserAssignedIdentity `Hashtable` + - Kind `String` + - Location `String` + - ManagedBy `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + +### AzResourceGroup [Export, Get, New, Remove, Set, Test, Update] `IResourceGroupExportResult, IResourceGroup, Boolean` + - ResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Id `String` + - Filter `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Option `String` + - Resource `String[]` + - Parameter `IExportTemplateRequest` + - Location `String` + - ManagedBy `String` + +### AzResourceLink [Get, New, Remove, Set] `IResourceLink, Boolean` + - ResourceId `String` + - InputObject `IResourcesIdentity` + - SubscriptionId `String[]` + - Scope `String` + - FilterById `String` + - FilterByScope `Filter` + - Note `String` + - TargetId `String` + - Parameter `IResourceLink` + +### AzResourceMove [Test] `Boolean` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + +### AzResourceProvider [Get, Register, Unregister] `IProvider` + - SubscriptionId `String[]` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + - Top `Int32` + +### AzResourceProviderOperationDetail [Get] `IResourceProviderOperationDefinition` + - ResourceProviderNamespace `String` + +### AzRoleAssignment [Get, New, Remove] `IRoleAssignment` + - Id `String` + - Name `String` + - Scope `String` + - RoleId `String` + - InputObject `IResourcesIdentity` + - ParentResourceId `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - ExpandPrincipalGroups `String` + - ServicePrincipalName `String` + - SignInName `String` + - Filter `String` + - CanDelegate `SwitchParameter` + - PrincipalId `String` + - RoleDefinitionId `String` + - Parameter `IRoleAssignmentCreateParameters` + - PrincipalType `PrincipalType` + +### AzRoleDefinition [Get, New, Remove, Set] `IRoleDefinition` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Custom `SwitchParameter` + - Filter `String` + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - RoleDefinition `IRoleDefinition` + +### AzSubscriptionLocation [Get] `ILocation` + - SubscriptionId `String[]` + +### AzTag [Get, New, Remove] `ITagDetails, Boolean` + - SubscriptionId `String[]` + - Name `String` + - Value `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + +### AzTenantBackfill [Start] `ITenantBackfillStatusResult` + +### AzTenantBackfillStatus [Invoke] `ITenantBackfillStatusResult` + diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/ModelSurface.md @@ -0,0 +1,1645 @@ +### AddOwnerParameters \ [Api16] + - Url `String` + +### AdGroup \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - Mail `String` + - MailEnabled `Boolean?` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - SecurityEnabled `Boolean?` + +### AliasPathType [Api20180501] + - ApiVersion `String[]` + - Path `String` + +### AliasType [Api20180501] + - Name `String` + - Path `IAliasPathType[]` + +### Appliance [Api20160901Preview] + - DefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceArtifact [Api20160901Preview] + - Name `String` + - Type `ApplianceArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplianceDefinition [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplianceDefinitionListResult [Api20160901Preview] + - NextLink `String` + - Value `IApplianceDefinition[]` + +### ApplianceDefinitionProperties [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - PackageFileUri `String` + +### ApplianceListResult [Api20160901Preview] + - NextLink `String` + - Value `IAppliance[]` + +### AppliancePatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceProperties [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### AppliancePropertiesPatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplianceProviderAuthorization [Api20160901Preview] + - PrincipalId `String` + - RoleDefinitionId `String` + +### Application \ [Api16, Api20170901, Api20180601] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppId `String` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DefinitionId `String` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - Id `String` + - IdentifierUri `String[]` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - Kind `String` + - KnownClientApplication `String[]` + - Location `String` + - LogoutUrl `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - ObjectId `String` + - ObjectType `String` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - PasswordCredentials `IPasswordCredential[]` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - ProvisioningState `String` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + - WwwHomepage `String` + +### ApplicationArtifact [Api20170901] + - Name `String` + - Type `ApplicationArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplicationBase [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationCreateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationDefinition [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplicationDefinitionListResult [Api20180601] + - NextLink `String` + - Value `IApplicationDefinition[]` + +### ApplicationDefinitionProperties [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IsEnabled `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - PackageFileUri `String` + +### ApplicationListResult [Api16, Api20180601] + - NextLink `String` + - OdataNextLink `String` + - Value `IApplication[]` + +### ApplicationPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplicationProperties [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationPropertiesPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationProviderAuthorization [Api20170901] + - PrincipalId `String` + - RoleDefinitionId `String` + +### ApplicationUpdateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### AppRole [Api16] + - AllowedMemberType `String[]` + - Description `String` + - DisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Value `String` + +### BasicDependency [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### CheckGroupMembershipParameters \ [Api16] + - GroupId `String` + - MemberId `String` + +### CheckGroupMembershipResult \ [Api16] + - Value `Boolean?` + +### CheckNameAvailabilityRequest [Api20180301Preview] + - Name `String` + - Type `Type?` **{ProvidersMicrosoftManagementGroups}** + +### CheckNameAvailabilityResult [Api20180301Preview] + - Message `String` + - NameAvailable `Boolean?` + - Reason `Reason?` **{AlreadyExists, Invalid}** + +### ClassicAdministrator [Api20150701] + - EmailAddress `String` + - Id `String` + - Name `String` + - Role `String` + - Type `String` + +### ClassicAdministratorListResult [Api20150701] + - NextLink `String` + - Value `IClassicAdministrator[]` + +### ClassicAdministratorProperties [Api20150701] + - EmailAddress `String` + - Role `String` + +### ComponentsSchemasIdentityPropertiesUserassignedidentitiesAdditionalproperties [Api20180501] + - ClientId `String` + - PrincipalId `String` + +### CreateManagementGroupChildInfo [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### CreateManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### CreateManagementGroupProperties [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### CreateManagementGroupRequest [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### CreateParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### DebugSetting [Api20180501] + - DetailLevel `String` + +### DenyAssignment [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - Id `String` + - IsSystemProtected `Boolean?` + - Name `String` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + - Type `String` + +### DenyAssignmentListResult [Api20180701Preview] + - NextLink `String` + - Value `IDenyAssignment[]` + +### DenyAssignmentPermission [Api20180701Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### DenyAssignmentProperties [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - IsSystemProtected `Boolean?` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + +### Dependency [Api20180501] + - DependsOn `IBasicDependency[]` + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### Deployment [Api20180501] + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentExportResult [Api20180501] + - Template `IDeploymentExportResultTemplate` + +### DeploymentExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Id `String` + - Location `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - Name `String` + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + - Type `String` + +### DeploymentListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentExtended[]` + +### DeploymentOperation [Api20180501] + - Id `String` + - OperationId `String` + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationProperties [Api20180501] + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationsListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentOperation[]` + +### DeploymentProperties [Api20180501] + - DebugSettingDetailLevel `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentPropertiesExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentValidateResult [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DescendantInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - ParentId `String` + - Type `String` + +### DescendantInfoProperties [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### DescendantListResult [Api20180301Preview] + - NextLink `String` + - Value `IDescendantInfo[]` + +### DescendantParentGroupInfo [Api20180301Preview] + - Id `String` + +### DirectoryObject \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - ObjectId `String` + - ObjectType `String` + +### DirectoryObjectListResult [Api16] + - OdataNextLink `String` + - Value `IDirectoryObject[]` + +### Domain \ [Api16] + - AuthenticationType `String` + - IsDefault `Boolean?` + - IsVerified `Boolean?` + - Name `String` + +### DomainListResult [Api16] + - Value `IDomain[]` + +### EntityInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - InheritedPermission `String` + - Name `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + - Type `String` + +### EntityInfoProperties [Api20180301Preview] + - DisplayName `String` + - InheritedPermission `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + +### EntityListResult [Api20180301Preview] + - Count `Int32?` + - NextLink `String` + - Value `IEntityInfo[]` + +### EntityParentGroupInfo [Api20180301Preview] + - Id `String` + +### ErrorDetails [Api20180301Preview] + - Code `String` + - Detail `String` + - Message `String` + +### ErrorMessage [Api16] + - Message `String` + +### ErrorResponse [Api20160901Preview, Api20180301Preview] + - ErrorCode `String` + - ErrorDetail `String` + - ErrorMessage `String` + - HttpStatus `String` + +### ExportTemplateRequest [Api20180501] + - Option `String` + - Resource `String[]` + +### FeatureOperationsListResult [Api20151201] + - NextLink `String` + - Value `IFeatureResult[]` + +### FeatureProperties [Api20151201] + - State `String` + +### FeatureResult [Api20151201] + - Id `String` + - Name `String` + - State `String` + - Type `String` + +### GenericResource [Api20160901Preview, Api20180501] + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IdentityUserAssignedIdentity `IIdentityUserAssignedIdentities ` + - Kind `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### GetObjectsParameters \ [Api16] + - IncludeDirectoryObjectReference `Boolean?` + - ObjectId `String[]` + - Type `String[]` + +### GraphError [Api16] + - ErrorMessageValueMessage `String` + - OdataErrorCode `String` + +### GroupAddMemberParameters \ [Api16] + - Url `String` + +### GroupCreateParameters \ [Api16] + - DisplayName `String` + - MailEnabled `Boolean` + - MailNickname `String` + - SecurityEnabled `Boolean` + +### GroupGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### GroupGetMemberGroupsResult [Api16] + - Value `String[]` + +### GroupListResult [Api16] + - OdataNextLink `String` + - Value `IAdGroup[]` + +### HttpMessage [Api20180501] + - Content `IHttpMessageContent` + +### Identity [Api20160901Preview, Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - UserAssignedIdentity `IIdentityUserAssignedIdentities ` + +### Identity1 [Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + +### InformationalUrl [Api16] + - Marketing `String` + - Privacy `String` + - Support `String` + - TermsOfService `String` + +### KeyCredential \ [Api16] + - CustomKeyIdentifier `String` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Type `String` + - Usage `String` + - Value `String` + +### KeyCredentialListResult [Api16] + - Value `IKeyCredential[]` + +### KeyCredentialsUpdateParameters [Api16] + - Value `IKeyCredential[]` + +### Location [Api20160601] + - DisplayName `String` + - Id `String` + - Latitude `String` + - Longitude `String` + - Name `String` + - SubscriptionId `String` + +### LocationListResult [Api20160601] + - Value `ILocation[]` + +### ManagementGroup [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### ManagementGroupChildInfo [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### ManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### ManagementGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - TenantId `String` + - Type `String` + +### ManagementGroupInfoProperties [Api20180301Preview] + - DisplayName `String` + - TenantId `String` + +### ManagementGroupListResult [Api20180301Preview] + - NextLink `String` + - Value `IManagementGroupInfo[]` + +### ManagementGroupProperties [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### ManagementLockListResult [Api20160901] + - NextLink `String` + - Value `IManagementLockObject[]` + +### ManagementLockObject [Api20160901] + - Id `String` + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Name `String` + - Note `String` + - Owner `IManagementLockOwner[]` + - Type `String` + +### ManagementLockOwner [Api20160901] + - ApplicationId `String` + +### ManagementLockProperties [Api20160901] + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Note `String` + - Owner `IManagementLockOwner[]` + +### OAuth2Permission [Api16] + - AdminConsentDescription `String` + - AdminConsentDisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Type `String` + - UserConsentDescription `String` + - UserConsentDisplayName `String` + - Value `String` + +### OAuth2PermissionGrant [Api16] + - ClientId `String` + - ConsentType `ConsentType?` **{AllPrincipals, Principal}** + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + +### OAuth2PermissionGrantListResult [Api16] + - OdataNextLink `String` + - Value `IOAuth2PermissionGrant[]` + +### OdataError [Api16] + - Code `String` + - ErrorMessageValueMessage `String` + +### OnErrorDeployment [Api20180501] + - DeploymentName `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### OnErrorDeploymentExtended [Api20180501] + - DeploymentName `String` + - ProvisioningState `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### Operation [Api20151201, Api20180301Preview] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayResource `String` + - Name `String` + +### OperationDisplay [Api20151201] + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationDisplayProperties [Api20180301Preview] + - Description `String` + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationListResult [Api20151201, Api20180301Preview] + - NextLink `String` + - Value `IOperation[]` + +### OperationResults [Api20180301Preview] + - Id `String` + - Name `String` + - ProvisioningState `String` + - Type `String` + +### OperationResultsProperties [Api20180301Preview] + - ProvisioningState `String` + +### OptionalClaim [Api16] + - AdditionalProperty `IOptionalClaimAdditionalProperties` + - Essential `Boolean?` + - Name `String` + - Source `String` + +### OptionalClaims [Api16] + - AccessToken `IOptionalClaim[]` + - IdToken `IOptionalClaim[]` + - SamlToken `IOptionalClaim[]` + +### ParametersLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### ParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### PasswordCredential \ [Api16] + - CustomKeyIdentifier `Byte[]` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Value `String` + +### PasswordCredentialListResult [Api16] + - Value `IPasswordCredential[]` + +### PasswordCredentialsUpdateParameters [Api16] + - Value `IPasswordCredential[]` + +### PasswordProfile \ [Api16] + - ForceChangePasswordNextLogin `Boolean?` + - Password `String` + +### PatchManagementGroupRequest [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### Permission [Api20150701, Api201801Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### PermissionGetResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IPermission[]` + +### Plan [Api20160901Preview, Api20180501] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PlanPatchable [Api20160901Preview] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PolicyAssignment [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - Name `String` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + - SkuName `String` + - SkuTier `String` + - Type `String` + +### PolicyAssignmentListResult [Api20151101, Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyAssignment[]` + +### PolicyAssignmentProperties [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + +### PolicyDefinition [Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Name `String` + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Property `IPolicyDefinitionProperties` + - Type `String` + +### PolicyDefinitionListResult [Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyDefinition[]` + +### PolicyDefinitionProperties [Api20161201] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicyDefinitionReference [Api20180501] + - Parameter `IPolicyDefinitionReferenceParameters` + - PolicyDefinitionId `String` + +### PolicySetDefinition [Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Name `String` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Type `String` + +### PolicySetDefinitionListResult [Api20180501] + - NextLink `String` + - Value `IPolicySetDefinition[]` + +### PolicySetDefinitionProperties [Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicySku [Api20180501] + - Name `String` + - Tier `String` + +### PreAuthorizedApplication [Api16] + - AppId `String` + - Extension `IPreAuthorizedApplicationExtension[]` + - Permission `IPreAuthorizedApplicationPermission[]` + +### PreAuthorizedApplicationExtension [Api16] + - Condition `String[]` + +### PreAuthorizedApplicationPermission [Api16] + - AccessGrant `String[]` + - DirectAccessGrant `Boolean?` + +### Principal [Api20180701Preview] + - Id `String` + - Type `String` + +### Provider [Api20180501] + - Id `String` + - Namespace `String` + - RegistrationState `String` + - ResourceType `IProviderResourceType[]` + +### ProviderListResult [Api20180501] + - NextLink `String` + - Value `IProvider[]` + +### ProviderOperation [Api20150701, Api201801Preview] + - Description `String` + - DisplayName `String` + - IsDataAction `Boolean?` + - Name `String` + - Origin `String` + - Property `IProviderOperationProperties` + +### ProviderOperationsMetadata [Api20150701, Api201801Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - Operation `IProviderOperation[]` + - ResourceType `IResourceType[]` + - Type `String` + +### ProviderOperationsMetadataListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IProviderOperationsMetadata[]` + +### ProviderResourceType [Api20180501] + - Alias `IAliasType[]` + - ApiVersion `String[]` + - Location `String[]` + - Property `IProviderResourceTypeProperties ` + - ResourceType `String` + +### RequiredResourceAccess \ [Api16] + - ResourceAccess `IResourceAccess[]` + - ResourceAppId `String` + +### Resource [Api20160901Preview] + - Id `String` + - Location `String` + - Name `String` + - Tag `IResourceTags ` + - Type `String` + +### ResourceAccess \ [Api16] + - Id `String` + - Type `String` + +### ResourceGroup [Api20180501] + - Id `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupTags ` + - Type `String` + +### ResourceGroupExportResult [Api20180501] + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Template `IResourceGroupExportResultTemplate` + +### ResourceGroupListResult [Api20180501] + - NextLink `String` + - Value `IResourceGroup[]` + +### ResourceGroupPatchable [Api20180501] + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupPatchableTags ` + +### ResourceGroupProperties [Api20180501] + - ProvisioningState `String` + +### ResourceLink [Api20160901] + - Id `String` + - Name `String` + - Note `String` + - SourceId `String` + - TargetId `String` + - Type `IResourceLinkType` + +### ResourceLinkProperties [Api20160901] + - Note `String` + - SourceId `String` + - TargetId `String` + +### ResourceLinkResult [Api20160901] + - NextLink `String` + - Value `IResourceLink[]` + +### ResourceListResult [Api20180501] + - NextLink `String` + - Value `IGenericResource[]` + +### ResourceManagementErrorWithDetails [Api20180501] + - Code `String` + - Detail `IResourceManagementErrorWithDetails[]` + - Message `String` + - Target `String` + +### ResourceProviderOperationDefinition [Api20151101] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayPublisher `String` + - DisplayResource `String` + - Name `String` + +### ResourceProviderOperationDetailListResult [Api20151101] + - NextLink `String` + - Value `IResourceProviderOperationDefinition[]` + +### ResourceProviderOperationDisplayProperties [Api20151101] + - Description `String` + - Operation `String` + - Provider `String` + - Publisher `String` + - Resource `String` + +### ResourcesIdentity [Models] + - ApplianceDefinitionId `String` + - ApplianceDefinitionName `String` + - ApplianceId `String` + - ApplianceName `String` + - ApplicationDefinitionId `String` + - ApplicationDefinitionName `String` + - ApplicationId `String` + - ApplicationId1 `String` + - ApplicationName `String` + - ApplicationObjectId `String` + - DenyAssignmentId `String` + - DeploymentName `String` + - DomainName `String` + - FeatureName `String` + - GroupId `String` + - GroupObjectId `String` + - Id `String` + - LinkId `String` + - LockName `String` + - ManagementGroupId `String` + - MemberObjectId `String` + - ObjectId `String` + - OperationId `String` + - OwnerObjectId `String` + - ParentResourcePath `String` + - PolicyAssignmentId `String` + - PolicyAssignmentName `String` + - PolicyDefinitionName `String` + - PolicySetDefinitionName `String` + - ResourceGroupName `String` + - ResourceId `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - RoleAssignmentId `String` + - RoleAssignmentName `String` + - RoleDefinitionId `String` + - RoleId `String` + - Scope `String` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - TagName `String` + - TagValue `String` + - TenantId `String` + - UpnOrObjectId `String` + +### ResourcesMoveInfo [Api20180501] + - Resource `String[]` + - TargetResourceGroup `String` + +### ResourceType [Api20150701, Api201801Preview] + - DisplayName `String` + - Name `String` + - Operation `IProviderOperation[]` + +### RoleAssignment [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - Id `String` + - Name `String` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + - Type `String` + +### RoleAssignmentCreateParameters [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentListResult [Api20150701, Api20180901Preview] + - NextLink `String` + - Value `IRoleAssignment[]` + +### RoleAssignmentProperties [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentPropertiesWithScope [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + +### RoleDefinition [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Id `String` + - Name `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - Type `String` + +### RoleDefinitionListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IRoleDefinition[]` + +### RoleDefinitionProperties [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + +### ServicePrincipal \ [Api16] + - AccountEnabled `Boolean?` + - AlternativeName `String[]` + - AppDisplayName `String` + - AppId `String` + - AppOwnerTenantId `String` + - AppRole `IAppRole[]` + - AppRoleAssignmentRequired `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - Homepage `String` + - KeyCredentials `IKeyCredential[]` + - LogoutUrl `String` + - Name `String[]` + - Oauth2Permission `IOAuth2Permission[]` + - ObjectId `String` + - ObjectType `String` + - PasswordCredentials `IPasswordCredential[]` + - PreferredTokenSigningKeyThumbprint `String` + - PublisherName `String` + - ReplyUrl `String[]` + - SamlMetadataUrl `String` + - Tag `String[]` + - Type `String` + +### ServicePrincipalBase [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalCreateParameters [Api16] + - AccountEnabled `Boolean?` + - AppId `String` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalListResult [Api16] + - OdataNextLink `String` + - Value `IServicePrincipal[]` + +### ServicePrincipalObjectResult [Api16] + - OdataMetadata `String` + - Value `String` + +### ServicePrincipalUpdateParameters [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### SignInName \ [Api16] + - Type `String` + - Value `String` + +### Sku [Api20160901Preview, Api20180501] + - Capacity `Int32?` + - Family `String` + - Model `String` + - Name `String` + - Size `String` + - Tier `String` + +### Subscription [Api20160601] + - AuthorizationSource `String` + - DisplayName `String` + - Id `String` + - PolicyLocationPlacementId `String` + - PolicyQuotaId `String` + - PolicySpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + - State `SubscriptionState?` **{Deleted, Disabled, Enabled, PastDue, Warned}** + - SubscriptionId `String` + +### SubscriptionPolicies [Api20160601] + - LocationPlacementId `String` + - QuotaId `String` + - SpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + +### TagCount [Api20180501] + - Type `String` + - Value `Int32?` + +### TagDetails [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagName `String` + - Value `ITagValue[]` + +### TagsListResult [Api20180501] + - NextLink `String` + - Value `ITagDetails[]` + +### TagValue [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagValue1 `String` + +### TargetResource [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### TemplateLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### TenantBackfillStatusResult [Api20180301Preview] + - Status `Status?` **{Cancelled, Completed, Failed, NotStarted, NotStartedButGroupsExist, Started}** + - TenantId `String` + +### TenantIdDescription [Api20160601] + - Id `String` + - TenantId `String` + +### TenantListResult [Api20160601] + - NextLink `String` + - Value `ITenantIdDescription[]` + +### User \ [Api16] + - AccountEnabled `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - PrincipalName `String` + - SignInName `ISignInName[]` + - Surname `String` + - Type `UserType?` **{Guest, Member}** + - UsageLocation `String` + +### UserBase \ [Api16] + - GivenName `String` + - ImmutableId `String` + - Surname `String` + - UsageLocation `String` + - UserType `UserType?` **{Guest, Member}** + +### UserCreateParameters \ [Api16] + - AccountEnabled `Boolean` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + +### UserGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### UserGetMemberGroupsResult [Api16] + - Value `String[]` + +### UserListResult [Api16] + - OdataNextLink `String` + - Value `IUser[]` + +### UserUpdateParameters \ [Api16] + - AccountEnabled `Boolean?` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/tools/Resources/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/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/CodeSigning.Management/target/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase.Data/main.tsp b/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase.Data/main.tsp new file mode 100644 index 00000000000..940b56869be --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase.Data/main.tsp @@ -0,0 +1,40 @@ +import "../LiftrBase/main.tsp"; + +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-resource-manager"; + +using Azure.ResourceManager; +using TypeSpec.Versioning; +using LiftrBase; + +@versioned(LiftrBase.Data.Versions) +namespace LiftrBase.Data; + +@doc("Supported versions for LiftrBase.Data resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1 and LiftrBase.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v1_preview) + v1_preview: "2024-08-01-preview", +} + +@doc("Properties specific to Data Organization resource") +model OrganizationProperties is BaseResourceProperties { + @doc("Organization properties") + partnerOrganizationProperties?: PartnerOrganizationProperties; +} + +@doc("Properties specific to Partner's organization") +model PartnerOrganizationProperties { + @doc("Organization Id in partner's system") + organizationId?: string; + + @doc("Organization name in partner's system") + @pattern("^[a-zA-Z0-9][a-zA-Z0-9_\\-.: ]*$") + @minLength(1) + @maxLength(50) + organizationName: string; + + @doc("Single Sign On properties for the organization") + singleSignOnProperties?: SingleSignOnProperties; +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase/main.tsp b/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase/main.tsp new file mode 100644 index 00000000000..afbeebb9419 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/LiftrBase/main.tsp @@ -0,0 +1,157 @@ +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/versioning"; + +using Azure.ResourceManager; +using TypeSpec.Versioning; + +@versioned(LiftrBase.Versions) +namespace LiftrBase; + +@doc("Supported versions for LiftrBase resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + v1_preview: "2024-08-01-preview", +} + +@doc("Marketplace subscription status of a resource.") +union MarketplaceSubscriptionStatus { + string, + + @doc("Purchased but not yet activated") + PendingFulfillmentStart: "PendingFulfillmentStart", + + @doc("Marketplace subscription is activated") + Subscribed: "Subscribed", + + @doc("This state indicates that a customer's payment for the Marketplace service was not received") + Suspended: "Suspended", + + @doc("Customer has cancelled the subscription") + Unsubscribed: "Unsubscribed", +} + +@doc("A string that represents a URI.") +scalar Uri extends string; + +@doc("Marketplace details for an organization") +model MarketplaceDetails { + @doc("SaaS subscription id for the the marketplace offer") + subscriptionId?: string; + + @doc("Marketplace subscription status") + subscriptionStatus?: MarketplaceSubscriptionStatus; + + @doc("Offer details for the marketplace that is selected by the user") + offerDetails: OfferDetails; +} + +@doc("Offer details for the marketplace that is selected by the user") +model OfferDetails { + @doc("Publisher Id for the marketplace offer") + publisherId: string; + + @doc("Offer Id for the marketplace offer") + offerId: string; + + @doc("Plan Id for the marketplace offer") + planId: string; + + @doc("Plan Name for the marketplace offer") + planName?: string; + + @doc("Term Name for the marketplace offer") + termUnit?: string; + + @doc("Term Id for the marketplace offer") + termId?: string; +} + +@doc("Reusable representation of an email address.") +@pattern("^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\\.)+[A-Za-z]{2,}$") +scalar email extends string; + +@doc("User details for an organization") +model UserDetails { + @doc("First name of the user") + firstName?: string; + + @doc("Last name of the user") + lastName?: string; + + @doc("Email address of the user") + emailAddress?: email; + + @doc("User's principal name") + upn?: string; + + @doc("User's phone number") + phoneNumber?: string; +} + +@doc("Company details for an organization") +model CompanyDetails { + @doc("Company name") + companyName?: string; + + @doc("Country name of the company") + country?: string; + + @doc("Office address of the company") + officeAddress?: string; + + @doc("Business phone number of the company") + businessPhone?: string; + + @doc("Domain of the user") + domain?: string; + + @doc("Number of employees in the company") + numberOfEmployees?: int64; +} + +@doc("Base resource properties that can be extended for arm resources.") +model BaseResourceProperties { + @doc("Marketplace details of the resource.") + @visibility("create", "read") + marketplaceDetails: MarketplaceDetails; + + @doc("Details of the user.") + userDetails: UserDetails; + + @doc("Details of the company.") + companyDetails: CompanyDetails; + + @doc("Provisioning state of the resource.") + @visibility("read") + provisioningState?: ResourceProvisioningState; +} + +@doc("Properties specific to Single Sign On Resource") +model SingleSignOnProperties { + @doc("State of the Single Sign On for the organization") + singleSignOnState?: SingleSignOnStates; + + @doc("AAD enterprise application Id used to setup SSO") + enterpriseAppId?: string; + + @doc("URL for SSO to be used by the partner to redirect the user to their system") + singleSignOnUrl?: Uri; + + @doc("List of AAD domains fetched from Microsoft Graph for user.") + aadDomains?: string[]; +} + +@doc("Various states of the SSO resource") +union SingleSignOnStates { + string, + + @doc("Initial state of the SSO resource") + Initial: "Initial", + + @doc("SSO is enabled for the organization") + Enable: "Enable", + + @doc("SSO is disabled for the organization") + Disable: "Disable", +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/README.md new file mode 100644 index 00000000000..1888f2f6db2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/README.md @@ -0,0 +1,28 @@ +# Neon Postgres service typespec project + +## Getting started + +- environment setup: https://microsoft.github.io/typespec/introduction/installation + +## Generate Neon swagger + +## NPM registry authentication + +We have to use the Liftr Feed Service for NPM to fetch the typespec dependencies. +The `.npmrc` file configures the folder accordingly. + +in development, you can tell npm to use the standard public registry by specifying it: + +`npm install --registry https://registry.npmjs.org` + +then: + +`tsp compile .` + +## Development + +Always edit `tsp` files, and generate swagger, never edit the swagger directly. + +For generating examples use the following command: + +`oav generate-examples neon.json` diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/client.tsp b/tests-upgrade/tests-emitter/Neon.Postgres.Management/client.tsp new file mode 100644 index 00000000000..32bbc99107a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/client.tsp @@ -0,0 +1,24 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(Neon.Postgres, "NeonPostgresMgmtClient", "python"); +@@clientName(Neon.Postgres.OrganizationResource, "NeonOrganization", "csharp"); +@@clientName(LiftrBase.CompanyDetails, "NeonCompanyDetails", "csharp"); +@@clientName(LiftrBase.MarketplaceDetails, "NeonMarketplaceDetails", "csharp"); +@@clientName(LiftrBase.OfferDetails, "NeonOfferDetails", "csharp"); +@@clientName(LiftrBase.UserDetails, "NeonUserDetails", "csharp"); +@@clientName(LiftrBase.Data.OrganizationProperties, + "NeonOrganizationProperties", + "csharp" +); +@@clientName(Azure.ResourceManager.ResourceProvisioningState, + "NeonResourceProvisioningState", + "csharp" +); +@@clientName(LiftrBase.SingleSignOnProperties, + "NeonSingleSignOnProperties", + "csharp" +); +@@clientName(LiftrBase.SingleSignOnStates, "NeonSingleSignOnState", "csharp"); diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..0ed2a97f35d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-08-01-preview" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "ekvuojrpbuyogrikfuzyghio", + "isDataAction": true, + "display": { + "provider": "lvppuskqcdcoejwuvsqrloczvnouy", + "resource": "rvvd", + "operation": "odjjqnodcgszczpsdrhrpwmqssrybr", + "description": "bwmstukaiaoisiu" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "https://contoso.com/nextlink" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..b73e2422370 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,184 @@ +{ + "title": "Organizations_CreateOrUpdate", + "operationId": "Organizations_CreateOrUpdate", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487", + "resourceGroupName": "rgneon", + "organizationName": "XB-.:", + "resource": { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/2__.-", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + }, + "201": { + "headers": { + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/2__.-", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..d3574b959b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Delete_MaximumSet_Gen.json @@ -0,0 +1,18 @@ +{ + "title": "Organizations_Delete", + "operationId": "Organizations_Delete", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487", + "resourceGroupName": "rgneon", + "organizationName": "2_3" + }, + "responses": { + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..4c4eba3507e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Get_MaximumSet_Gen.json @@ -0,0 +1,73 @@ +{ + "title": "Organizations_Get", + "operationId": "Organizations_Get", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487", + "resourceGroupName": "rgneon", + "organizationName": "5" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/2__.-", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..3dfabedecd8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,77 @@ +{ + "title": "Organizations_ListByResourceGroup", + "operationId": "Organizations_ListByResourceGroup", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487", + "resourceGroupName": "rgneon" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/2__.-", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..c1d5f8609be --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,76 @@ +{ + "title": "Organizations_ListBySubscription", + "operationId": "Organizations_ListBySubscription", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "nrhvoqzulowcunhmvwfgjcaibvwcl", + "organizationName": "2__.-", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/2__.-", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..aa6b1e166e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/examples/2024-08-01-preview/Organizations_Update_MaximumSet_Gen.json @@ -0,0 +1,112 @@ +{ + "title": "Organizations_Update", + "operationId": "Organizations_Update", + "parameters": { + "api-version": "2024-08-01-preview", + "subscriptionId": "1178323D-8270-4757-B639-D528B6266487", + "resourceGroupName": "rgneon", + "organizationName": "eRY-J_:", + "properties": { + "properties": { + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "partnerOrganizationProperties": { + "organizationId": "njyoqflcmfwzfsqe", + "organizationName": "J:.._3P", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key8990": "wuvaontoqyttxtikvvahdegcfdfkz" + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "subscriptionId": "yxmkfivp", + "subscriptionStatus": "PendingFulfillmentStart", + "offerDetails": { + "publisherId": "hporaxnopmolttlnkbarw", + "offerId": "bunyeeupoedueofwrzej", + "planId": "nlbfiwtslenfwek", + "planName": "ljbmgpkfqklaufacbpml", + "termUnit": "qbcq", + "termId": "aedlchikwqckuploswthvshe" + } + }, + "userDetails": { + "firstName": "buwwe", + "lastName": "escynjpynkoox", + "emailAddress": "3i_%@w8-y.H-p.tvj.dG", + "upn": "fwedjamgwwrotcjaucuzdwycfjdqn", + "phoneNumber": "dlrqoowumy" + }, + "companyDetails": { + "companyName": "uxn", + "country": "lpajqzptqchuko", + "officeAddress": "chpkrlpmfslmawgunjxdllzcrctykq", + "businessPhone": "hbeb", + "domain": "krjldeakhwiepvs", + "numberOfEmployees": 23 + }, + "provisioningState": "Succeeded", + "partnerOrganizationProperties": { + "organizationId": "njyoqflcmfwzfsqe", + "organizationName": "J:.._3P", + "singleSignOnProperties": { + "singleSignOnState": "Initial", + "enterpriseAppId": "fpibacregjfncfdsojs", + "singleSignOnUrl": "tmojh", + "aadDomains": [ + "kndszgrwzbvvlssvkej" + ] + } + } + }, + "tags": { + "key2099": "omjjymaqtrqzksxszhzgyl" + }, + "location": "upxxgikyqrbnv", + "id": "/subscriptions/1178323D-8270-4757-B639-D528B6266487/resourceGroups/rgneon/providers/Microsoft.Neon/organizations/eRY-J_:", + "name": "grhdqtqnkqmu", + "type": "gapeymltyvlqlvpgdgfxidkkd", + "systemData": { + "createdBy": "qfhekdgpvdtqcohjhvlyhzd", + "createdByType": "User", + "createdAt": "2024-07-30T15:12:24.902Z", + "lastModifiedBy": "dqsjroejrtucfjyqcoonpdopfaa", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-07-30T15:12:24.902Z" + } + } + }, + "202": { + "headers": { + "location": "https://contoso.com/operationstatus" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/main.tsp b/tests-upgrade/tests-emitter/Neon.Postgres.Management/main.tsp new file mode 100644 index 00000000000..f6171830148 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/main.tsp @@ -0,0 +1,53 @@ +import "./LiftrBase.Data/main.tsp"; + +import "@azure-tools/typespec-autorest"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Http; +using TypeSpec.Rest; +using Azure.ResourceManager; +using TypeSpec.Versioning; +using LiftrBase.Data; + +@armProviderNamespace +@service({ + title: "Neon.Postgres", + description: "Azure Native Services Integration for Neon Postgres", +}) +@versioned(Neon.Postgres.Versions) +@armCommonTypesVersion("v5") +namespace Neon.Postgres; + +@doc("Supported API versions for the Neon.Postgres resource provider.") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1, LiftrBase.Versions.v1_preview, LiftrBase.Data.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v1_preview) + @useDependency(LiftrBase.Data.Versions.v1_preview) + v1_preview: "2024-08-01-preview", +} + +interface Operations extends Azure.ResourceManager.Operations {} + +@doc("Organization Resource by Neon") +model OrganizationResource is TrackedResource { + @key("organizationName") + @pattern("^[a-zA-Z0-9][a-zA-Z0-9_\\-.: ]*$") + @segment("organizations") + @minLength(1) + @maxLength(50) + @doc("Name of the Neon Organizations resource") + @path + name: string; +} + +@armResourceOperations +interface Organizations { + get is ArmResourceRead; + createOrUpdate is ArmResourceCreateOrUpdateAsync; + update is ArmResourcePatchAsync; + delete is ArmResourceDeleteWithoutOkAsync; + listByResourceGroup is ArmResourceListByParent; + listBySubscription is ArmListBySubscription; +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/.gitattributes b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.csproj b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.csproj new file mode 100644 index 00000000000..341515b66ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.NeonPostgres.private + false + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres + true + false + ./bin + $(OutputPath) + Az.NeonPostgres.nuspec + true + + + 1998, 1591 + true + + + + false + TRACE;DEBUG;NETSTANDARD + + + + true + true + MSSharedLibKey.snk + TRACE;RELEASE;NETSTANDARD;SIGN + + + + + + + + + $(DefaultItemExcludes);resources/** + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.nuspec b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.nuspec new file mode 100644 index 00000000000..9e45adb8bfe --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.nuspec @@ -0,0 +1,32 @@ + + + + Az.NeonPostgres + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: NeonPostgres cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Sphere + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.psm1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.psm1 new file mode 100644 index 00000000000..e141e652d39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/Az.NeonPostgres.psm1 @@ -0,0 +1,119 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.NeonPostgres.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/README.md new file mode 100644 index 00000000000..ad46fee26d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/README.md @@ -0,0 +1,24 @@ + +# Az.NeonPostgres +This directory contains the PowerShell module for the NeonPostgres service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.NeonPostgres`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/build-module.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/build-module.ps1 new file mode 100644 index 00000000000..c68a9150473 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $NotIsolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +$isAzure = [System.Convert]::ToBoolean('true') + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.NeonPostgres.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.NeonPostgres.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.NeonPostgres.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.NeonPostgres' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: NeonPostgres cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.NeonPostgres.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and ((-not (Test-Path -Path $resourceModule)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..37c591e8b9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if (''.length -gt 0) { + $ModuleName = '' + } else { + $ModuleName = 'Az.NeonPostgres' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('NeonPostgres')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'NeonPostgres' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/Az.NeonPostgres.custom.psm1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/Az.NeonPostgres.custom.psm1 new file mode 100644 index 00000000000..7b5d3cf9240 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/Az.NeonPostgres.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.NeonPostgres.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/README.md new file mode 100644 index 00000000000..a2b2d2306ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.NeonPostgres` 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.NeonPostgres.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.NeonPostgres` 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.NeonPostgres.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.NeonPostgres.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.NeonPostgres`. 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.NeonPostgres.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.NeonPostgres`. +- `Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.NeonPostgres`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/docs/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/docs/README.md new file mode 100644 index 00000000000..9b75b830dbd --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.NeonPostgres` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.NeonPostgres` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/examples/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/export-surface.ps1 new file mode 100644 index 00000000000..f0a993f554f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.NeonPostgres.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.NeonPostgres' +$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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/exports/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/exports/README.md new file mode 100644 index 00000000000..e06cddf1fcf --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.NeonPostgres`. No other cmdlets in this repository are directly exported. What that means is the `Az.NeonPostgres` module will run [Export-ModuleMember](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.NeonPostgres.private.dll`) and from the `..\custom\Az.NeonPostgres.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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-help.ps1 new file mode 100644 index 00000000000..1ec00335982 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.NeonPostgres.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.NeonPostgres.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..61605cecace --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generate-portal-ux.ps1 @@ -0,0 +1,383 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.NeonPostgres' +$rootModuleName = '' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + if ($Null -eq $example) + { + $example = @() + } + + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + if ($Null -eq $signature) + { + $signature = @() + } + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/Module.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/Module.cs new file mode 100644 index 00000000000..9f341a12387 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/Module.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + public bool _useProxy = false; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.NeonPostgres"; + + /// 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.NeonPostgres"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_useProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..38bd81ba869 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.PowerShell.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial class Any + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Any(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Any(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Any(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Any(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial interface IAny + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..e7eca7b3e5c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Any.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Any.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..069c0344c7d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..2652931e5dd --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Any.json.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Anything + public partial class Any + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new Any(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.PowerShell.cs new file mode 100644 index 00000000000..cc55e9a5289 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Company details for an organization + [System.ComponentModel.TypeConverter(typeof(CompanyDetailsTypeConverter))] + public partial class CompanyDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal CompanyDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).CompanyName = (string) content.GetValueForProperty("CompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).CompanyName, global::System.Convert.ToString); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("OfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).OfficeAddress = (string) content.GetValueForProperty("OfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).OfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("BusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).BusinessPhone = (string) content.GetValueForProperty("BusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).BusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("Domain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Domain = (string) content.GetValueForProperty("Domain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Domain, global::System.Convert.ToString); + } + if (content.Contains("NumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).NumberOfEmployee = (long?) content.GetValueForProperty("NumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).NumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal CompanyDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).CompanyName = (string) content.GetValueForProperty("CompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).CompanyName, global::System.Convert.ToString); + } + if (content.Contains("Country")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Country = (string) content.GetValueForProperty("Country",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Country, global::System.Convert.ToString); + } + if (content.Contains("OfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).OfficeAddress = (string) content.GetValueForProperty("OfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).OfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("BusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).BusinessPhone = (string) content.GetValueForProperty("BusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).BusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("Domain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Domain = (string) content.GetValueForProperty("Domain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).Domain, global::System.Convert.ToString); + } + if (content.Contains("NumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).NumberOfEmployee = (long?) content.GetValueForProperty("NumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)this).NumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + 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.NeonPostgres.Models.ICompanyDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new CompanyDetails(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.NeonPostgres.Models.ICompanyDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new CompanyDetails(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.NeonPostgres.Models.ICompanyDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Company details for an organization + [System.ComponentModel.TypeConverter(typeof(CompanyDetailsTypeConverter))] + public partial interface ICompanyDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.TypeConverter.cs new file mode 100644 index 00000000000..30d49fcb22d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class CompanyDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return CompanyDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return CompanyDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return CompanyDetails.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.cs new file mode 100644 index 00000000000..adfb24ad9cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Company details for an organization + public partial class CompanyDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal + { + + /// Backing field for property. + private string _businessPhone; + + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string BusinessPhone { get => this._businessPhone; set => this._businessPhone = value; } + + /// Backing field for property. + private string _companyName; + + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string CompanyName { get => this._companyName; set => this._companyName = value; } + + /// Backing field for property. + private string _country; + + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Country { get => this._country; set => this._country = value; } + + /// Backing field for property. + private string _domain; + + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Domain { get => this._domain; set => this._domain = value; } + + /// Backing field for property. + private long? _numberOfEmployee; + + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public long? NumberOfEmployee { get => this._numberOfEmployee; set => this._numberOfEmployee = value; } + + /// Backing field for property. + private string _officeAddress; + + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string OfficeAddress { get => this._officeAddress; set => this._officeAddress = value; } + + /// Creates an new instance. + public CompanyDetails() + { + + } + } + /// Company details for an organization + public partial interface ICompanyDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + string BusinessPhone { get; set; } + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + string CompanyName { get; set; } + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + string Country { get; set; } + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + string Domain { get; set; } + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + long? NumberOfEmployee { get; set; } + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + string OfficeAddress { get; set; } + + } + /// Company details for an organization + internal partial interface ICompanyDetailsInternal + + { + /// Business phone number of the company + string BusinessPhone { get; set; } + /// Company name + string CompanyName { get; set; } + /// Country name of the company + string Country { get; set; } + /// Domain of the user + string Domain { get; set; } + /// Number of employees in the company + long? NumberOfEmployee { get; set; } + /// Office address of the company + string OfficeAddress { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.json.cs new file mode 100644 index 00000000000..d6a3dd15fe2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/CompanyDetails.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Company details for an organization + public partial class CompanyDetails + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal CompanyDetails(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_companyName = If( json?.PropertyT("companyName"), out var __jsonCompanyName) ? (string)__jsonCompanyName : (string)_companyName;} + {_country = If( json?.PropertyT("country"), out var __jsonCountry) ? (string)__jsonCountry : (string)_country;} + {_officeAddress = If( json?.PropertyT("officeAddress"), out var __jsonOfficeAddress) ? (string)__jsonOfficeAddress : (string)_officeAddress;} + {_businessPhone = If( json?.PropertyT("businessPhone"), out var __jsonBusinessPhone) ? (string)__jsonBusinessPhone : (string)_businessPhone;} + {_domain = If( json?.PropertyT("domain"), out var __jsonDomain) ? (string)__jsonDomain : (string)_domain;} + {_numberOfEmployee = If( json?.PropertyT("numberOfEmployees"), out var __jsonNumberOfEmployees) ? (long?)__jsonNumberOfEmployees : _numberOfEmployee;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new CompanyDetails(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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._companyName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._companyName.ToString()) : null, "companyName" ,container.Add ); + AddIf( null != (((object)this._country)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._country.ToString()) : null, "country" ,container.Add ); + AddIf( null != (((object)this._officeAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._officeAddress.ToString()) : null, "officeAddress" ,container.Add ); + AddIf( null != (((object)this._businessPhone)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._businessPhone.ToString()) : null, "businessPhone" ,container.Add ); + AddIf( null != (((object)this._domain)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._domain.ToString()) : null, "domain" ,container.Add ); + AddIf( null != this._numberOfEmployee ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNumber((long)this._numberOfEmployee) : null, "numberOfEmployees" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..c41018ce416 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial class ErrorAdditionalInfo + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorAdditionalInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorAdditionalInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial interface IErrorAdditionalInfo + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..106cb02de1e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorAdditionalInfoTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorAdditionalInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..d085710ff73 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorAdditionalInfo() + { + + } + } + /// The resource management error additional info. + public partial interface IErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info.", + SerializedName = @"info", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource management error additional info. + internal partial interface IErrorAdditionalInfoInternal + + { + /// The additional info. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IAny Info { get; set; } + /// The additional info type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..c3af6f471b3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorAdditionalInfo.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_info = If( json?.PropertyT("info"), out var __jsonInfo) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new ErrorAdditionalInfo(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._info.ToJson(null,serializationMode) : null, "info" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..2fa24d41706 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial class ErrorDetail + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetail(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetail(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial interface IErrorDetail + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..eac167c74f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetail.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..9786c9c3f64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public System.Collections.Generic.List AdditionalInfo { get => this._additionalInfo; } + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Creates an new instance. + public ErrorDetail() + { + + } + } + /// The error detail. + public partial interface IErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// The error detail. + internal partial interface IErrorDetailInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..76c730db19f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorDetail.json.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new ErrorDetail(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.XNodeArray(); + foreach( var __s in this._additionalInfo ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("additionalInfo",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..0724a28b5ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial class ErrorResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Target, 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 + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal)this).Target, 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.NeonPostgres.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..19b3980f4a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..89abb436727 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).AdditionalInfo = value; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Code = value; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Message = value; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Target = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + internal partial interface IErrorResponseInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..dc9e1703034 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/ErrorResponse.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs new file mode 100644 index 00000000000..fa3bdfba6bd --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs @@ -0,0 +1,226 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Marketplace details for an organization + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial class MarketplaceDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MarketplaceDetails(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.NeonPostgres.Models.IMarketplaceDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MarketplaceDetails(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.NeonPostgres.Models.IMarketplaceDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MarketplaceDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("OfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("OfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus = (string) content.GetValueForProperty("SubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId, 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 MarketplaceDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("OfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("OfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("SubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus = (string) content.GetValueForProperty("SubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).SubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)this).OfferDetailTermId, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Marketplace details for an organization + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial interface IMarketplaceDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs new file mode 100644 index 00000000000..6823c4e8fbf --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MarketplaceDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MarketplaceDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MarketplaceDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MarketplaceDetails.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.cs new file mode 100644 index 00000000000..59cffb33a26 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.cs @@ -0,0 +1,188 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Marketplace details for an organization + public partial class MarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal + { + + /// Internal Acessors for OfferDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal.OfferDetail { get => (this._offerDetail = this._offerDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetails()); set { {_offerDetail = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails _offerDetail; + + /// Offer details for the marketplace that is selected by the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails OfferDetail { get => (this._offerDetail = this._offerDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetails()); set => this._offerDetail = value; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).OfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).OfferId = value ; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PlanId = value ; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).PublisherId = value ; } + + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).TermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).TermId = value ?? null; } + + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)OfferDetail).TermUnit = value ?? null; } + + /// Backing field for property. + private string _subscriptionId; + + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Backing field for property. + private string _subscriptionStatus; + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string SubscriptionStatus { get => this._subscriptionStatus; set => this._subscriptionStatus = value; } + + /// Creates an new instance. + public MarketplaceDetails() + { + + } + } + /// Marketplace details for an organization + public partial interface IMarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string SubscriptionStatus { get; set; } + + } + /// Marketplace details for an organization + internal partial interface IMarketplaceDetailsInternal + + { + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails OfferDetail { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// SaaS subscription id for the the marketplace offer + string SubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string SubscriptionStatus { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.json.cs new file mode 100644 index 00000000000..9f38f13a411 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/MarketplaceDetails.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Marketplace details for an organization + public partial class MarketplaceDetails + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new MarketplaceDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal MarketplaceDetails(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_offerDetail = If( json?.PropertyT("offerDetails"), out var __jsonOfferDetails) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetails.FromJson(__jsonOfferDetails) : _offerDetail;} + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_subscriptionStatus = If( json?.PropertyT("subscriptionStatus"), out var __jsonSubscriptionStatus) ? (string)__jsonSubscriptionStatus : (string)_subscriptionStatus;} + 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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._offerDetail ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._offerDetail.ToJson(null,serializationMode) : null, "offerDetails" ,container.Add ); + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._subscriptionStatus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._subscriptionStatus.ToString()) : null, "subscriptionStatus" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.PowerShell.cs new file mode 100644 index 00000000000..9b6332f10aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.PowerShell.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(NeonPostgresIdentityTypeConverter))] + public partial class NeonPostgresIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new NeonPostgresIdentity(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.NeonPostgres.Models.INeonPostgresIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new NeonPostgresIdentity(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.NeonPostgres.Models.INeonPostgresIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal NeonPostgresIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)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 NeonPostgresIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal)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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(NeonPostgresIdentityTypeConverter))] + public partial interface INeonPostgresIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.TypeConverter.cs new file mode 100644 index 00000000000..07daf6e7810 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.TypeConverter.cs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class NeonPostgresIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity 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 NeonPostgresIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return NeonPostgresIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return NeonPostgresIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return NeonPostgresIdentity.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.cs new file mode 100644 index 00000000000..bda6324cb0b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class NeonPostgresIdentity : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentityInternal + { + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Id { get => this._id; set => this._id = value; } + + /// Backing field for property. + private string _organizationName; + + /// Name of the Neon Organizations resource + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string OrganizationName { get => this._organizationName; set => this._organizationName = value; } + + /// Backing field for property. + private string _resourceGroupName; + + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public NeonPostgresIdentity() + { + + } + } + public partial interface INeonPostgresIdentity : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// Name of the Neon Organizations resource + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string OrganizationName { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + 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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface INeonPostgresIdentityInternal + + { + /// Resource identity path + string Id { get; set; } + /// Name of the Neon Organizations resource + string OrganizationName { get; set; } + /// The name of the resource group. The name is case insensitive. + string ResourceGroupName { get; set; } + /// The ID of the target subscription. The value must be an UUID. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.json.cs new file mode 100644 index 00000000000..5e07592b72d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/NeonPostgresIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class NeonPostgresIdentity + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new NeonPostgresIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal NeonPostgresIdentity(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)_resourceGroupName;} + {_organizationName = If( json?.PropertyT("organizationName"), out var __jsonOrganizationName) ? (string)__jsonOrganizationName : (string)_organizationName;} + {_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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._organizationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._organizationName.ToString()) : null, "organizationName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.PowerShell.cs new file mode 100644 index 00000000000..ddaf44b4153 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Offer details for the marketplace that is selected by the user + [System.ComponentModel.TypeConverter(typeof(OfferDetailsTypeConverter))] + public partial class OfferDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OfferDetails(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.NeonPostgres.Models.IOfferDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OfferDetails(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.NeonPostgres.Models.IOfferDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OfferDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("PlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanName, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermId = (string) content.GetValueForProperty("TermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermId, 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 OfferDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("PlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanName = (string) content.GetValueForProperty("PlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).PlanName, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("TermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermId = (string) content.GetValueForProperty("TermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal)this).TermId, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Offer details for the marketplace that is selected by the user + [System.ComponentModel.TypeConverter(typeof(OfferDetailsTypeConverter))] + public partial interface IOfferDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs new file mode 100644 index 00000000000..8e6193049e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OfferDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OfferDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OfferDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OfferDetails.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.cs new file mode 100644 index 00000000000..e5d9a3fb548 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Offer details for the marketplace that is selected by the user + public partial class OfferDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetailsInternal + { + + /// Backing field for property. + private string _offerId; + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string OfferId { get => this._offerId; set => this._offerId = value; } + + /// Backing field for property. + private string _planId; + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string PlanId { get => this._planId; set => this._planId = value; } + + /// Backing field for property. + private string _planName; + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string PlanName { get => this._planName; set => this._planName = value; } + + /// Backing field for property. + private string _publisherId; + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string PublisherId { get => this._publisherId; set => this._publisherId = value; } + + /// Backing field for property. + private string _termId; + + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string TermId { get => this._termId; set => this._termId = value; } + + /// Backing field for property. + private string _termUnit; + + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string TermUnit { get => this._termUnit; set => this._termUnit = value; } + + /// Creates an new instance. + public OfferDetails() + { + + } + } + /// Offer details for the marketplace that is selected by the user + public partial interface IOfferDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string PlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string PlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string PublisherId { get; set; } + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string TermId { get; set; } + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// Offer details for the marketplace that is selected by the user + internal partial interface IOfferDetailsInternal + + { + /// Offer Id for the marketplace offer + string OfferId { get; set; } + /// Plan Id for the marketplace offer + string PlanId { get; set; } + /// Plan Name for the marketplace offer + string PlanName { get; set; } + /// Publisher Id for the marketplace offer + string PublisherId { get; set; } + /// Term Id for the marketplace offer + string TermId { get; set; } + /// Term Name for the marketplace offer + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.json.cs new file mode 100644 index 00000000000..f264ad78e65 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OfferDetails.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Offer details for the marketplace that is selected by the user + public partial class OfferDetails + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OfferDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OfferDetails(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_publisherId = If( json?.PropertyT("publisherId"), out var __jsonPublisherId) ? (string)__jsonPublisherId : (string)_publisherId;} + {_offerId = If( json?.PropertyT("offerId"), out var __jsonOfferId) ? (string)__jsonOfferId : (string)_offerId;} + {_planId = If( json?.PropertyT("planId"), out var __jsonPlanId) ? (string)__jsonPlanId : (string)_planId;} + {_planName = If( json?.PropertyT("planName"), out var __jsonPlanName) ? (string)__jsonPlanName : (string)_planName;} + {_termUnit = If( json?.PropertyT("termUnit"), out var __jsonTermUnit) ? (string)__jsonTermUnit : (string)_termUnit;} + {_termId = If( json?.PropertyT("termId"), out var __jsonTermId) ? (string)__jsonTermId : (string)_termId;} + 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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._publisherId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._publisherId.ToString()) : null, "publisherId" ,container.Add ); + AddIf( null != (((object)this._offerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._offerId.ToString()) : null, "offerId" ,container.Add ); + AddIf( null != (((object)this._planId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._planId.ToString()) : null, "planId" ,container.Add ); + AddIf( null != (((object)this._planName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._planName.ToString()) : null, "planName" ,container.Add ); + AddIf( null != (((object)this._termUnit)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._termUnit.ToString()) : null, "termUnit" ,container.Add ); + AddIf( null != (((object)this._termId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._termId.ToString()) : null, "termId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..0af77984966 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.PowerShell.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial class Operation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Operation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Operation(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Operation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..15e7363a5ab --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Operation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Operation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..049f74f7665 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal + { + + /// Backing field for property. + private string _actionType; + + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; set => this._actionType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationDisplay()); } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Description; } + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Operation; } + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Provider; } + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Resource; } + + /// Backing field for property. + private bool? _isDataAction; + + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Extensible enum. Indicates the action type. ""Internal"" refers to actions that are for internal only APIs.", + SerializedName = @"actionType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Whether the operation applies to data-plane. This is ""true"" for data-plane operations and ""false"" for Azure Resource Manager/control-plane operations.", + SerializedName = @"isDataAction", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDataAction { get; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the operation, as per Resource-Based Access Control (RBAC). Examples: ""Microsoft.Compute/virtualMachines/write"", ""Microsoft.Compute/virtualMachines/capture/action""", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is ""user,system""", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; } + + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + internal partial interface IOperationInternal + + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay Display { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string DisplayOperation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string DisplayResource { get; set; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + bool? IsDataAction { get; set; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + string Name { get; set; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..efb69f20308 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Operation.json.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Models.OperationDisplay.FromJson(__jsonDisplay) : _display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_isDataAction = If( json?.PropertyT("isDataAction"), out var __jsonIsDataAction) ? (bool?)__jsonIsDataAction : _isDataAction;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)_origin;} + {_actionType = If( json?.PropertyT("actionType"), out var __jsonActionType) ? (string)__jsonActionType : (string)_actionType;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._actionType.ToString()) : null, "actionType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..90431ee5bb4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial class OperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDisplay(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDisplay(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..fb7c724428a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..98c108614de --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Localized display information for and operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Localized display information for and operation. + internal partial interface IOperationDisplayInternal + + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string Description { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string Operation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string Provider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..cbae479fd26 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationDisplay.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Localized display information for and 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)_provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)_resource;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)_operation;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..6cd87df51b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial class OperationListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..15ce1ce6a6b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..26cbc1d1ed7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Operation items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation) })] + System.Collections.Generic.List Value { get; set; } + + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + internal partial interface IOperationListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Operation items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..d332c7e6c18 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OperationListResult.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Operation.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.PowerShell.cs new file mode 100644 index 00000000000..d3fc77db4c9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Properties specific to Data Organization resource + [System.ComponentModel.TypeConverter(typeof(OrganizationPropertiesTypeConverter))] + public partial class OrganizationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationProperties(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.NeonPostgres.Models.IOrganizationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationProperties(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.NeonPostgres.Models.IOrganizationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CompanyDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails) content.GetValueForProperty("CompanyDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("MarketplaceDetailOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetailEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailEmailAddress = (string) content.GetValueForProperty("UserDetailEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailFirstName = (string) content.GetValueForProperty("UserDetailFirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailLastName = (string) content.GetValueForProperty("UserDetailLastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailLastName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailUpn = (string) content.GetValueForProperty("UserDetailUpn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailUpn, global::System.Convert.ToString); + } + if (content.Contains("UserDetailPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailPhoneNumber = (string) content.GetValueForProperty("UserDetailPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCompanyName = (string) content.GetValueForProperty("CompanyDetailCompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCompanyName, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCountry = (string) content.GetValueForProperty("CompanyDetailCountry",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCountry, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailOfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailOfficeAddress = (string) content.GetValueForProperty("CompanyDetailOfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailOfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailBusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailBusinessPhone = (string) content.GetValueForProperty("CompanyDetailBusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailBusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailDomain = (string) content.GetValueForProperty("CompanyDetailDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailDomain, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailNumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailNumberOfEmployee = (long?) content.GetValueForProperty("CompanyDetailNumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailNumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, 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 OrganizationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CompanyDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails) content.GetValueForProperty("CompanyDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("MarketplaceDetailOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetailEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailEmailAddress = (string) content.GetValueForProperty("UserDetailEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).MarketplaceDetailSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailFirstName = (string) content.GetValueForProperty("UserDetailFirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailLastName = (string) content.GetValueForProperty("UserDetailLastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailLastName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailUpn = (string) content.GetValueForProperty("UserDetailUpn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailUpn, global::System.Convert.ToString); + } + if (content.Contains("UserDetailPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailPhoneNumber = (string) content.GetValueForProperty("UserDetailPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).UserDetailPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCompanyName = (string) content.GetValueForProperty("CompanyDetailCompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCompanyName, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCountry = (string) content.GetValueForProperty("CompanyDetailCountry",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailCountry, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailOfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailOfficeAddress = (string) content.GetValueForProperty("CompanyDetailOfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailOfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailBusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailBusinessPhone = (string) content.GetValueForProperty("CompanyDetailBusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailBusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailDomain = (string) content.GetValueForProperty("CompanyDetailDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailDomain, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailNumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailNumberOfEmployee = (long?) content.GetValueForProperty("CompanyDetailNumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).CompanyDetailNumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Data Organization resource + [System.ComponentModel.TypeConverter(typeof(OrganizationPropertiesTypeConverter))] + public partial interface IOrganizationProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs new file mode 100644 index 00000000000..58540c781f1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationProperties.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.cs new file mode 100644 index 00000000000..5abb3960401 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.cs @@ -0,0 +1,544 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Data Organization resource + public partial class OrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails _companyDetail; + + /// Details of the company. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails CompanyDetail { get => (this._companyDetail = this._companyDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetails()); set => this._companyDetail = value; } + + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailBusinessPhone { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).BusinessPhone; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).BusinessPhone = value ?? null; } + + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailCompanyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).CompanyName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).CompanyName = value ?? null; } + + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailCountry { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).Country; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).Country = value ?? null; } + + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).Domain; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).Domain = value ?? null; } + + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public long? CompanyDetailNumberOfEmployee { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).NumberOfEmployee; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).NumberOfEmployee = value ?? default(long); } + + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailOfficeAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).OfficeAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetailsInternal)CompanyDetail).OfficeAddress = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails _marketplaceDetail; + + /// Marketplace details of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetails()); set => this._marketplaceDetail = value; } + + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string MarketplaceDetailSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).SubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).SubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string MarketplaceDetailSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).SubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).SubscriptionStatus = value ?? null; } + + /// Internal Acessors for CompanyDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.CompanyDetail { get => (this._companyDetail = this._companyDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetails()); set { {_companyDetail = value;} } } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetails()); set { {_marketplaceDetail = value;} } } + + /// Internal Acessors for MarketplaceDetailOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.MarketplaceDetailOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetail = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationProperties()); set { {_partnerOrganizationProperty = value;} } } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnProperty = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal.UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetails()); set { {_userDetail = value;} } } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailOfferId = value ; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPlanId = value ; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailPublisherId = value ; } + + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailTermId = value ?? null; } + + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferDetailTermUnit = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties _partnerOrganizationProperty; + + /// Organization properties + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get => (this._partnerOrganizationProperty = this._partnerOrganizationProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationProperties()); set => this._partnerOrganizationProperty = value; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).OrganizationName = value ?? null; } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)PartnerOrganizationProperty).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails _userDetail; + + /// Details of the user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetails()); set => this._userDetail = value; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).EmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).EmailAddress = value ?? null; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).FirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).FirstName = value ?? null; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).LastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).LastName = value ?? null; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).PhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).PhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).Upn; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)UserDetail).Upn = value ?? null; } + + /// Creates an new instance. + public OrganizationProperties() + { + + } + } + /// Properties specific to Data Organization resource + public partial interface IOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailBusinessPhone { get; set; } + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailCompanyName { get; set; } + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailCountry { get; set; } + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailDomain { get; set; } + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + long? CompanyDetailNumberOfEmployee { get; set; } + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailOfficeAddress { get; set; } + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailSubscriptionStatus { get; set; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning state of the resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserDetailFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserDetailLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserDetailPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserDetailUpn { get; set; } + + } + /// Properties specific to Data Organization resource + internal partial interface IOrganizationPropertiesInternal + + { + /// Details of the company. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails CompanyDetail { get; set; } + /// Business phone number of the company + string CompanyDetailBusinessPhone { get; set; } + /// Company name + string CompanyDetailCompanyName { get; set; } + /// Country name of the company + string CompanyDetailCountry { get; set; } + /// Domain of the user + string CompanyDetailDomain { get; set; } + /// Number of employees in the company + long? CompanyDetailNumberOfEmployee { get; set; } + /// Office address of the company + string CompanyDetailOfficeAddress { get; set; } + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails MarketplaceDetailOfferDetail { get; set; } + /// SaaS subscription id for the the marketplace offer + string MarketplaceDetailSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailSubscriptionStatus { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails UserDetail { get; set; } + /// Email address of the user + string UserDetailEmailAddress { get; set; } + /// First name of the user + string UserDetailFirstName { get; set; } + /// Last name of the user + string UserDetailLastName { get; set; } + /// User's phone number + string UserDetailPhoneNumber { get; set; } + /// User's principal name + string UserDetailUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.json.cs new file mode 100644 index 00000000000..80393c57eea --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationProperties.json.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Data Organization resource + public partial class OrganizationProperties + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OrganizationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationProperties(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplaceDetail = If( json?.PropertyT("marketplaceDetails"), out var __jsonMarketplaceDetails) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetails.FromJson(__jsonMarketplaceDetails) : _marketplaceDetail;} + {_userDetail = If( json?.PropertyT("userDetails"), out var __jsonUserDetails) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetails.FromJson(__jsonUserDetails) : _userDetail;} + {_companyDetail = If( json?.PropertyT("companyDetails"), out var __jsonCompanyDetails) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetails.FromJson(__jsonCompanyDetails) : _companyDetail;} + {_partnerOrganizationProperty = If( json?.PropertyT("partnerOrganizationProperties"), out var __jsonPartnerOrganizationProperties) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationProperties.FromJson(__jsonPartnerOrganizationProperties) : _partnerOrganizationProperty;} + {_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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != this._marketplaceDetail ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._marketplaceDetail.ToJson(null,serializationMode) : null, "marketplaceDetails" ,container.Add ); + } + AddIf( null != this._userDetail ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._userDetail.ToJson(null,serializationMode) : null, "userDetails" ,container.Add ); + AddIf( null != this._companyDetail ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._companyDetail.ToJson(null,serializationMode) : null, "companyDetails" ,container.Add ); + AddIf( null != this._partnerOrganizationProperty ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._partnerOrganizationProperty.ToJson(null,serializationMode) : null, "partnerOrganizationProperties" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs new file mode 100644 index 00000000000..b7bd5bec5e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.PowerShell.cs @@ -0,0 +1,530 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Organization Resource by Neon + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceTypeConverter))] + public partial class OrganizationResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResource(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.NeonPostgres.Models.IOrganizationResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResource(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.NeonPostgres.Models.IOrganizationResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CompanyDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails) content.GetValueForProperty("CompanyDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("MarketplaceDetailOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetailEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailEmailAddress = (string) content.GetValueForProperty("UserDetailEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailFirstName = (string) content.GetValueForProperty("UserDetailFirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailLastName = (string) content.GetValueForProperty("UserDetailLastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailLastName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailUpn = (string) content.GetValueForProperty("UserDetailUpn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailUpn, global::System.Convert.ToString); + } + if (content.Contains("UserDetailPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailPhoneNumber = (string) content.GetValueForProperty("UserDetailPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCompanyName = (string) content.GetValueForProperty("CompanyDetailCompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCompanyName, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCountry = (string) content.GetValueForProperty("CompanyDetailCountry",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCountry, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailOfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailOfficeAddress = (string) content.GetValueForProperty("CompanyDetailOfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailOfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailBusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailBusinessPhone = (string) content.GetValueForProperty("CompanyDetailBusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailBusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailDomain = (string) content.GetValueForProperty("CompanyDetailDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailDomain, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailNumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailNumberOfEmployee = (long?) content.GetValueForProperty("CompanyDetailNumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailNumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl, 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 OrganizationResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("CompanyDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails) content.GetValueForProperty("CompanyDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.CompanyDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties) content.GetValueForProperty("PartnerOrganizationProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.PartnerOrganizationPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailOfferDetail = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails) content.GetValueForProperty("MarketplaceDetailOfferDetail",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailOfferDetail, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OfferDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetailEmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailEmailAddress = (string) content.GetValueForProperty("UserDetailEmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailEmailAddress, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).MarketplaceDetailSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailFirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailFirstName = (string) content.GetValueForProperty("UserDetailFirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailFirstName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailLastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailLastName = (string) content.GetValueForProperty("UserDetailLastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailLastName, global::System.Convert.ToString); + } + if (content.Contains("UserDetailUpn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailUpn = (string) content.GetValueForProperty("UserDetailUpn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailUpn, global::System.Convert.ToString); + } + if (content.Contains("UserDetailPhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailPhoneNumber = (string) content.GetValueForProperty("UserDetailPhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).UserDetailPhoneNumber, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCompanyName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCompanyName = (string) content.GetValueForProperty("CompanyDetailCompanyName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCompanyName, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailCountry")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCountry = (string) content.GetValueForProperty("CompanyDetailCountry",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailCountry, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailOfficeAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailOfficeAddress = (string) content.GetValueForProperty("CompanyDetailOfficeAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailOfficeAddress, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailBusinessPhone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailBusinessPhone = (string) content.GetValueForProperty("CompanyDetailBusinessPhone",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailBusinessPhone, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailDomain = (string) content.GetValueForProperty("CompanyDetailDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailDomain, global::System.Convert.ToString); + } + if (content.Contains("CompanyDetailNumberOfEmployee")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailNumberOfEmployee = (long?) content.GetValueForProperty("CompanyDetailNumberOfEmployee",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).CompanyDetailNumberOfEmployee, (__y)=> (long) global::System.Convert.ChangeType(__y, typeof(long))); + } + if (content.Contains("PartnerOrganizationPropertySingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("PartnerOrganizationPropertySingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertySingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationId, global::System.Convert.ToString); + } + if (content.Contains("PartnerOrganizationPropertyOrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName = (string) content.GetValueForProperty("PartnerOrganizationPropertyOrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).PartnerOrganizationPropertyOrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("OfferDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId = (string) content.GetValueForProperty("OfferDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailOfferId = (string) content.GetValueForProperty("OfferDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanId = (string) content.GetValueForProperty("OfferDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailPlanName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanName = (string) content.GetValueForProperty("OfferDetailPlanName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailPlanName, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit = (string) content.GetValueForProperty("OfferDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("OfferDetailTermId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermId = (string) content.GetValueForProperty("OfferDetailTermId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).OfferDetailTermId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).SingleSignOnPropertySingleSignOnUrl, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Organization Resource by Neon + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceTypeConverter))] + public partial interface IOrganizationResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs new file mode 100644 index 00000000000..b7f778a7db6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResource.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.cs new file mode 100644 index 00000000000..e0e4337c5ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.cs @@ -0,0 +1,664 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Organization Resource by Neon + public partial class OrganizationResource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IValidates, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TrackedResource(); + + /// Backing field for property. + private string _azureAsyncOperation; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string AzureAsyncOperation { get => this._azureAsyncOperation; set => this._azureAsyncOperation = value; } + + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailBusinessPhone { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailBusinessPhone; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailBusinessPhone = value ?? null; } + + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailCompanyName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailCompanyName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailCompanyName = value ?? null; } + + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailCountry { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailCountry; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailCountry = value ?? null; } + + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailDomain = value ?? null; } + + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public long? CompanyDetailNumberOfEmployee { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailNumberOfEmployee; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailNumberOfEmployee = value ?? default(long); } + + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string CompanyDetailOfficeAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailOfficeAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetailOfficeAddress = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Id; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)__trackedResource).Location = value ; } + + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string MarketplaceDetailSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string MarketplaceDetailSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailSubscriptionStatus = value ?? null; } + + /// Internal Acessors for CompanyDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.CompanyDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).CompanyDetail = value; } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.MarketplaceDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetail = value; } + + /// Internal Acessors for MarketplaceDetailOfferDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.MarketplaceDetailOfferDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailOfferDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).MarketplaceDetailOfferDetail = value; } + + /// Internal Acessors for PartnerOrganizationProperty + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.PartnerOrganizationProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationProperty = value; } + + /// Internal Acessors for PartnerOrganizationPropertySingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.PartnerOrganizationPropertySingleSignOnProperty { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertySingleSignOnProperty = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal.UserDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetail = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Name; } + + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailOfferId = value ?? null; } + + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanId = value ?? null; } + + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPlanName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPlanName = value ?? null; } + + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailPublisherId = value ?? null; } + + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermId = value ?? null; } + + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string OfferDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).OfferDetailTermUnit = value ?? null; } + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationId = value ?? null; } + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string PartnerOrganizationPropertyOrganizationName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).PartnerOrganizationPropertyOrganizationName = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationProperties()); set => this._property = value; } + + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyAadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyAadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertyEnterpriseAppId = value ?? null; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).SingleSignOnPropertySingleSignOnUrl = value ?? null; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)__trackedResource).Tag = value ?? null /* model class */; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__trackedResource).Type; } + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailEmailAddress { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailEmailAddress; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailEmailAddress = value ?? null; } + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailFirstName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailFirstName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailFirstName = value ?? null; } + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailLastName { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailLastName; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailLastName = value ?? null; } + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailPhoneNumber { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailPhoneNumber; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailPhoneNumber = value ?? null; } + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string UserDetailUpn { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailUpn; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationPropertiesInternal)Property).UserDetailUpn = value ?? null; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Azure-AsyncOperation", out var __azureAsyncOperationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).AzureAsyncOperation = System.Linq.Enumerable.FirstOrDefault(__azureAsyncOperationHeader0) is string __headerAzureAsyncOperationHeader0 ? __headerAzureAsyncOperationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// Creates an new instance. + public OrganizationResource() + { + + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Organization Resource by Neon + public partial interface IOrganizationResource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource + { + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Azure-AsyncOperation", + PossibleTypes = new [] { typeof(string) })] + string AzureAsyncOperation { get; set; } + /// Business phone number of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailBusinessPhone { get; set; } + /// Company name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailCompanyName { get; set; } + /// Country name of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailCountry { get; set; } + /// Domain of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailDomain { get; set; } + /// Number of employees in the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + long? CompanyDetailNumberOfEmployee { get; set; } + /// Office address of the company + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + string CompanyDetailOfficeAddress { get; set; } + /// SaaS subscription id for the the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailSubscriptionStatus { get; set; } + /// Offer Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = false, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string OfferDetailTermUnit { get; set; } + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Provisioning state of the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning state of the resource.", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string UserDetailFirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string UserDetailLastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string UserDetailPhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string UserDetailUpn { get; set; } + + } + /// Organization Resource by Neon + internal partial interface IOrganizationResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal + { + string AzureAsyncOperation { get; set; } + /// Details of the company. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ICompanyDetails CompanyDetail { get; set; } + /// Business phone number of the company + string CompanyDetailBusinessPhone { get; set; } + /// Company name + string CompanyDetailCompanyName { get; set; } + /// Country name of the company + string CompanyDetailCountry { get; set; } + /// Domain of the user + string CompanyDetailDomain { get; set; } + /// Number of employees in the company + long? CompanyDetailNumberOfEmployee { get; set; } + /// Office address of the company + string CompanyDetailOfficeAddress { get; set; } + /// Marketplace details of the resource. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Offer details for the marketplace that is selected by the user + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOfferDetails MarketplaceDetailOfferDetail { get; set; } + /// SaaS subscription id for the the marketplace offer + string MarketplaceDetailSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailSubscriptionStatus { get; set; } + /// Offer Id for the marketplace offer + string OfferDetailOfferId { get; set; } + /// Plan Id for the marketplace offer + string OfferDetailPlanId { get; set; } + /// Plan Name for the marketplace offer + string OfferDetailPlanName { get; set; } + /// Publisher Id for the marketplace offer + string OfferDetailPublisherId { get; set; } + /// Term Id for the marketplace offer + string OfferDetailTermId { get; set; } + /// Term Name for the marketplace offer + string OfferDetailTermUnit { get; set; } + /// Organization properties + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties PartnerOrganizationProperty { get; set; } + /// Organization Id in partner's system + string PartnerOrganizationPropertyOrganizationId { get; set; } + /// Organization name in partner's system + string PartnerOrganizationPropertyOrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties PartnerOrganizationPropertySingleSignOnProperty { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationProperties Property { get; set; } + /// Provisioning state of the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Succeeded", "Failed", "Canceled")] + string ProvisioningState { get; set; } + + int? RetryAfter { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + /// Details of the user. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails UserDetail { get; set; } + /// Email address of the user + string UserDetailEmailAddress { get; set; } + /// First name of the user + string UserDetailFirstName { get; set; } + /// Last name of the user + string UserDetailLastName { get; set; } + /// User's phone number + string UserDetailPhoneNumber { get; set; } + /// User's principal name + string UserDetailUpn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.json.cs new file mode 100644 index 00000000000..e3c47119fd0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResource.json.cs @@ -0,0 +1,108 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Organization Resource by Neon + public partial class OrganizationResource + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OrganizationResource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResource(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationProperties.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs new file mode 100644 index 00000000000..39f9f4e8c75 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// The response of a OrganizationResource list operation. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceListResultTypeConverter))] + public partial class OrganizationResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationResourceListResult(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.NeonPostgres.Models.IOrganizationResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationResourceListResult(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.NeonPostgres.Models.IOrganizationResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationResourceListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationResourceListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The response of a OrganizationResource list operation. + [System.ComponentModel.TypeConverter(typeof(OrganizationResourceListResultTypeConverter))] + public partial interface IOrganizationResourceListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs new file mode 100644 index 00000000000..916a6789a08 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.TypeConverter.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationResourceListResult.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.cs new file mode 100644 index 00000000000..63f6ce6985f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The response of a OrganizationResource list operation. + public partial class OrganizationResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The OrganizationResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OrganizationResourceListResult() + { + + } + } + /// The response of a OrganizationResource list operation. + public partial interface IOrganizationResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The OrganizationResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The OrganizationResource items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a OrganizationResource list operation. + internal partial interface IOrganizationResourceListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The OrganizationResource items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs new file mode 100644 index 00000000000..bf5cd0ed0f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationResourceListResult.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// The response of a OrganizationResource list operation. + public partial class OrganizationResourceListResult + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OrganizationResourceListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource) (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..870749839a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(OrganizationsDeleteAcceptedResponseHeadersTypeConverter))] + public partial class OrganizationsDeleteAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationsDeleteAcceptedResponseHeaders(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.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationsDeleteAcceptedResponseHeaders(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.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationsDeleteAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationsDeleteAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(OrganizationsDeleteAcceptedResponseHeadersTypeConverter))] + public partial interface IOrganizationsDeleteAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..7eebaf15943 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationsDeleteAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationsDeleteAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationsDeleteAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationsDeleteAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..6bc7bce7714 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class OrganizationsDeleteAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// + /// Creates an new instance. + /// + public OrganizationsDeleteAcceptedResponseHeaders() + { + + } + } + public partial interface IOrganizationsDeleteAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface IOrganizationsDeleteAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..4c73888a3e4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsDeleteAcceptedResponseHeaders.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class OrganizationsDeleteAcceptedResponseHeaders + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsDeleteAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OrganizationsDeleteAcceptedResponseHeaders(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationsDeleteAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..8a50a99b037 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(OrganizationsUpdateAcceptedResponseHeadersTypeConverter))] + public partial class OrganizationsUpdateAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OrganizationsUpdateAcceptedResponseHeaders(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.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OrganizationsUpdateAcceptedResponseHeaders(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.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OrganizationsUpdateAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OrganizationsUpdateAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(OrganizationsUpdateAcceptedResponseHeadersTypeConverter))] + public partial interface IOrganizationsUpdateAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..d30e287f3d0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OrganizationsUpdateAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OrganizationsUpdateAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OrganizationsUpdateAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OrganizationsUpdateAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..0284dff9aae --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class OrganizationsUpdateAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Location", out var __locationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader0) is string __headerLocationHeader0 ? __headerLocationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// + /// Creates an new instance. + /// + public OrganizationsUpdateAcceptedResponseHeaders() + { + + } + } + public partial interface IOrganizationsUpdateAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface IOrganizationsUpdateAcceptedResponseHeadersInternal + + { + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..89b444d320a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/OrganizationsUpdateAcceptedResponseHeaders.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class OrganizationsUpdateAcceptedResponseHeaders + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationsUpdateAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new OrganizationsUpdateAcceptedResponseHeaders(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal OrganizationsUpdateAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs new file mode 100644 index 00000000000..0048c064048 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.PowerShell.cs @@ -0,0 +1,210 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Properties specific to Partner's organization + [System.ComponentModel.TypeConverter(typeof(PartnerOrganizationPropertiesTypeConverter))] + public partial class PartnerOrganizationProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new PartnerOrganizationProperties(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.NeonPostgres.Models.IPartnerOrganizationProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new PartnerOrganizationProperties(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.NeonPostgres.Models.IPartnerOrganizationProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal PartnerOrganizationProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("SingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("OrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId = (string) content.GetValueForProperty("OrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, 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 PartnerOrganizationProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnProperty")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties) content.GetValueForProperty("SingleSignOnProperty",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnProperty, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnPropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("OrganizationId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId = (string) content.GetValueForProperty("OrganizationId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationId, global::System.Convert.ToString); + } + if (content.Contains("OrganizationName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName = (string) content.GetValueForProperty("OrganizationName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).OrganizationName, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyAadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain = (System.Collections.Generic.List) content.GetValueForProperty("SingleSignOnPropertyAadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyAadDomain, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("SingleSignOnPropertySingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertyEnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId = (string) content.GetValueForProperty("SingleSignOnPropertyEnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertyEnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnPropertySingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnPropertySingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal)this).SingleSignOnPropertySingleSignOnUrl, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Partner's organization + [System.ComponentModel.TypeConverter(typeof(PartnerOrganizationPropertiesTypeConverter))] + public partial interface IPartnerOrganizationProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs new file mode 100644 index 00000000000..666a107fdd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class PartnerOrganizationPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return PartnerOrganizationProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return PartnerOrganizationProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return PartnerOrganizationProperties.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.cs new file mode 100644 index 00000000000..8b38a52725d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Partner's organization + public partial class PartnerOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal + { + + /// Internal Acessors for SingleSignOnProperty + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationPropertiesInternal.SingleSignOnProperty { get => (this._singleSignOnProperty = this._singleSignOnProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnProperties()); set { {_singleSignOnProperty = value;} } } + + /// Backing field for property. + private string _organizationId; + + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string OrganizationId { get => this._organizationId; set => this._organizationId = value; } + + /// Backing field for property. + private string _organizationName; + + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string OrganizationName { get => this._organizationName; set => this._organizationName = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties _singleSignOnProperty; + + /// Single Sign On properties for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties SingleSignOnProperty { get => (this._singleSignOnProperty = this._singleSignOnProperty ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnProperties()); set => this._singleSignOnProperty = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public System.Collections.Generic.List SingleSignOnPropertyAadDomain { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).AadDomain; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).AadDomain = value ?? null /* arrayOf */; } + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertyEnterpriseAppId { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).EnterpriseAppId; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).EnterpriseAppId = value ?? null; } + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnState { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnState; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnState = value ?? null; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SingleSignOnPropertySingleSignOnUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)SingleSignOnProperty).SingleSignOnUrl = value ?? null; } + + /// Creates an new instance. + public PartnerOrganizationProperties() + { + + } + } + /// Properties specific to Partner's organization + public partial interface IPartnerOrganizationProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Organization Id in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + string OrganizationId { get; set; } + /// Organization name in partner's system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + string OrganizationName { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnPropertySingleSignOnUrl { get; set; } + + } + /// Properties specific to Partner's organization + internal partial interface IPartnerOrganizationPropertiesInternal + + { + /// Organization Id in partner's system + string OrganizationId { get; set; } + /// Organization name in partner's system + string OrganizationName { get; set; } + /// Single Sign On properties for the organization + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties SingleSignOnProperty { get; set; } + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List SingleSignOnPropertyAadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string SingleSignOnPropertyEnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnPropertySingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnPropertySingleSignOnUrl { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.json.cs new file mode 100644 index 00000000000..67fbb50b8a8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/PartnerOrganizationProperties.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Partner's organization + public partial class PartnerOrganizationProperties + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IPartnerOrganizationProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new PartnerOrganizationProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal PartnerOrganizationProperties(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_singleSignOnProperty = If( json?.PropertyT("singleSignOnProperties"), out var __jsonSingleSignOnProperties) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SingleSignOnProperties.FromJson(__jsonSingleSignOnProperties) : _singleSignOnProperty;} + {_organizationId = If( json?.PropertyT("organizationId"), out var __jsonOrganizationId) ? (string)__jsonOrganizationId : (string)_organizationId;} + {_organizationName = If( json?.PropertyT("organizationName"), out var __jsonOrganizationName) ? (string)__jsonOrganizationName : (string)_organizationName;} + 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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._singleSignOnProperty ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._singleSignOnProperty.ToJson(null,serializationMode) : null, "singleSignOnProperties" ,container.Add ); + AddIf( null != (((object)this._organizationId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._organizationId.ToString()) : null, "organizationId" ,container.Add ); + AddIf( null != (((object)this._organizationName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._organizationName.ToString()) : null, "organizationName" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..e5969906a4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Resource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Resource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..77f810ff91e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Resource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Resource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Resource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..a93df517f92 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.cs @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataLastModifiedBy { get; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of the resource. E.g. ""Microsoft.Compute/virtualMachines"" or ""Microsoft.Storage/storageAccounts""", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData SystemData { get; set; } + /// The timestamp of resource creation (UTC). + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// The identity that last modified the resource. + string SystemDataLastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..850f8e94a95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Resource.json.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs new file mode 100644 index 00000000000..74d2592b1d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Properties specific to Single Sign On Resource + [System.ComponentModel.TypeConverter(typeof(SingleSignOnPropertiesTypeConverter))] + public partial class SingleSignOnProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SingleSignOnProperties(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.NeonPostgres.Models.ISingleSignOnProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SingleSignOnProperties(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.NeonPostgres.Models.ISingleSignOnProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SingleSignOnProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState = (string) content.GetValueForProperty("SingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId = (string) content.GetValueForProperty("EnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("AadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).AadDomain = (System.Collections.Generic.List) content.GetValueForProperty("AadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).AadDomain, __y => TypeConverterExtensions.SelectToList(__y, 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 SingleSignOnProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SingleSignOnState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState = (string) content.GetValueForProperty("SingleSignOnState",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnState, global::System.Convert.ToString); + } + if (content.Contains("EnterpriseAppId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId = (string) content.GetValueForProperty("EnterpriseAppId",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).EnterpriseAppId, global::System.Convert.ToString); + } + if (content.Contains("SingleSignOnUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl = (string) content.GetValueForProperty("SingleSignOnUrl",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).SingleSignOnUrl, global::System.Convert.ToString); + } + if (content.Contains("AadDomain")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).AadDomain = (System.Collections.Generic.List) content.GetValueForProperty("AadDomain",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal)this).AadDomain, __y => TypeConverterExtensions.SelectToList(__y, 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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to Single Sign On Resource + [System.ComponentModel.TypeConverter(typeof(SingleSignOnPropertiesTypeConverter))] + public partial interface ISingleSignOnProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs new file mode 100644 index 00000000000..a1caff3667c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SingleSignOnPropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SingleSignOnProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SingleSignOnProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SingleSignOnProperties.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.cs new file mode 100644 index 00000000000..a03e99de5c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Single Sign On Resource + public partial class SingleSignOnProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnPropertiesInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _aadDomain; + + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public System.Collections.Generic.List AadDomain { get => this._aadDomain; set => this._aadDomain = value; } + + /// Backing field for property. + private string _enterpriseAppId; + + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string EnterpriseAppId { get => this._enterpriseAppId; set => this._enterpriseAppId = value; } + + /// Backing field for property. + private string _singleSignOnState; + + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string SingleSignOnState { get => this._singleSignOnState; set => this._singleSignOnState = value; } + + /// Backing field for property. + private string _singleSignOnUrl; + + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string SingleSignOnUrl { get => this._singleSignOnUrl; set => this._singleSignOnUrl = value; } + + /// Creates an new instance. + public SingleSignOnProperties() + { + + } + } + /// Properties specific to Single Sign On Resource + public partial interface ISingleSignOnProperties : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// List of AAD domains fetched from Microsoft Graph for user. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List AadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + string EnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + string SingleSignOnUrl { get; set; } + + } + /// Properties specific to Single Sign On Resource + internal partial interface ISingleSignOnPropertiesInternal + + { + /// List of AAD domains fetched from Microsoft Graph for user. + System.Collections.Generic.List AadDomain { get; set; } + /// AAD enterprise application Id used to setup SSO + string EnterpriseAppId { get; set; } + /// State of the Single Sign On for the organization + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + string SingleSignOnState { get; set; } + /// URL for SSO to be used by the partner to redirect the user to their system + string SingleSignOnUrl { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.json.cs new file mode 100644 index 00000000000..bef8eccf125 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SingleSignOnProperties.json.cs @@ -0,0 +1,120 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Properties specific to Single Sign On Resource + public partial class SingleSignOnProperties + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISingleSignOnProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new SingleSignOnProperties(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal SingleSignOnProperties(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_singleSignOnState = If( json?.PropertyT("singleSignOnState"), out var __jsonSingleSignOnState) ? (string)__jsonSingleSignOnState : (string)_singleSignOnState;} + {_enterpriseAppId = If( json?.PropertyT("enterpriseAppId"), out var __jsonEnterpriseAppId) ? (string)__jsonEnterpriseAppId : (string)_enterpriseAppId;} + {_singleSignOnUrl = If( json?.PropertyT("singleSignOnUrl"), out var __jsonSingleSignOnUrl) ? (string)__jsonSingleSignOnUrl : (string)_singleSignOnUrl;} + {_aadDomain = If( json?.PropertyT("aadDomains"), out var __jsonAadDomains) ? If( __jsonAadDomains as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(string) (__u is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _aadDomain;} + 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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._singleSignOnState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._singleSignOnState.ToString()) : null, "singleSignOnState" ,container.Add ); + AddIf( null != (((object)this._enterpriseAppId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._enterpriseAppId.ToString()) : null, "enterpriseAppId" ,container.Add ); + AddIf( null != (((object)this._singleSignOnUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._singleSignOnUrl.ToString()) : null, "singleSignOnUrl" ,container.Add ); + if (null != this._aadDomain) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.XNodeArray(); + foreach( var __x in this._aadDomain ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("aadDomains",__w); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..1c0fb5a8d0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..80f264ff210 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..9967734024b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; set => this._createdAt = value; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; set => this._createdBy = value; } + + /// Backing field for property. + private string _createdByType; + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; set => this._createdByType = value; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; set => this._lastModifiedAt = value; } + + /// Backing field for property. + private string _lastModifiedBy; + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string LastModifiedBy { get => this._lastModifiedBy; set => this._lastModifiedBy = value; } + + /// Backing field for property. + private string _lastModifiedByType; + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string LastModifiedByType { get => this._lastModifiedByType; set => this._lastModifiedByType = value; } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp of resource creation (UTC). + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..6ca5eefafcc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/SystemData.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_lastModifiedBy = If( json?.PropertyT("lastModifiedBy"), out var __jsonLastModifiedBy) ? (string)__jsonLastModifiedBy : (string)_lastModifiedBy;} + {_lastModifiedByType = If( json?.PropertyT("lastModifiedByType"), out var __jsonLastModifiedByType) ? (string)__jsonLastModifiedByType : (string)_lastModifiedByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + AddIf( null != (((object)this._lastModifiedBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.PowerShell.cs new file mode 100644 index 00000000000..a7623ce620a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// Resource tags. + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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.NeonPostgres.Models.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.NeonPostgres.Models.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 + // 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 Tags(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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.TypeConverter.cs new file mode 100644 index 00000000000..a49a30f6a0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.cs new file mode 100644 index 00000000000..fa234e46a0a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Resource tags. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITagsInternal + { + + /// Creates an new instance. + public Tags() + { + + } + } + /// Resource tags. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.dictionary.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.dictionary.cs new file mode 100644 index 00000000000..91190f91f8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Models.Tags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.json.cs new file mode 100644 index 00000000000..025adc9b42a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/Tags.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// Resource tags. + 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags. + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..8ef1af503f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.PowerShell.cs @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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.NeonPostgres.Models.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.NeonPostgres.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// 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 + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..c01b0500d6d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..7243ec70516 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Tags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.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 that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = 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.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get; set; } + + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..7029de254ed --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/TrackedResource.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.Tags.FromJson(__jsonTags) : _tag;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.PowerShell.cs new file mode 100644 index 00000000000..d0f4e0d7ee9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// User details for an organization + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial class UserDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserDetails(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.NeonPostgres.Models.IUserDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserDetails(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.NeonPostgres.Models.IUserDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("FirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).FirstName = (string) content.GetValueForProperty("FirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).FirstName, global::System.Convert.ToString); + } + if (content.Contains("LastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).LastName = (string) content.GetValueForProperty("LastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).LastName, global::System.Convert.ToString); + } + if (content.Contains("EmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).EmailAddress = (string) content.GetValueForProperty("EmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).EmailAddress, global::System.Convert.ToString); + } + if (content.Contains("Upn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).Upn = (string) content.GetValueForProperty("Upn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).Upn, global::System.Convert.ToString); + } + if (content.Contains("PhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).PhoneNumber = (string) content.GetValueForProperty("PhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).PhoneNumber, 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 UserDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("FirstName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).FirstName = (string) content.GetValueForProperty("FirstName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).FirstName, global::System.Convert.ToString); + } + if (content.Contains("LastName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).LastName = (string) content.GetValueForProperty("LastName",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).LastName, global::System.Convert.ToString); + } + if (content.Contains("EmailAddress")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).EmailAddress = (string) content.GetValueForProperty("EmailAddress",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).EmailAddress, global::System.Convert.ToString); + } + if (content.Contains("Upn")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).Upn = (string) content.GetValueForProperty("Upn",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).Upn, global::System.Convert.ToString); + } + if (content.Contains("PhoneNumber")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).PhoneNumber = (string) content.GetValueForProperty("PhoneNumber",((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal)this).PhoneNumber, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// User details for an organization + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial interface IUserDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.TypeConverter.cs new file mode 100644 index 00000000000..ba1de0957f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserDetails.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.cs new file mode 100644 index 00000000000..4a8904e9900 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// User details for an organization + public partial class UserDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetailsInternal + { + + /// Backing field for property. + private string _emailAddress; + + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string EmailAddress { get => this._emailAddress; set => this._emailAddress = value; } + + /// Backing field for property. + private string _firstName; + + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string FirstName { get => this._firstName; set => this._firstName = value; } + + /// Backing field for property. + private string _lastName; + + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string LastName { get => this._lastName; set => this._lastName = value; } + + /// Backing field for property. + private string _phoneNumber; + + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string PhoneNumber { get => this._phoneNumber; set => this._phoneNumber = value; } + + /// Backing field for property. + private string _upn; + + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Origin(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PropertyOrigin.Owned)] + public string Upn { get => this._upn; set => this._upn = value; } + + /// Creates an new instance. + public UserDetails() + { + + } + } + /// User details for an organization + public partial interface IUserDetails : + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IJsonSerializable + { + /// Email address of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + string EmailAddress { get; set; } + /// First name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + string FirstName { get; set; } + /// Last name of the user + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + string LastName { get; set; } + /// User's phone number + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + string PhoneNumber { get; set; } + /// User's principal name + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + string Upn { get; set; } + + } + /// User details for an organization + internal partial interface IUserDetailsInternal + + { + /// Email address of the user + string EmailAddress { get; set; } + /// First name of the user + string FirstName { get; set; } + /// Last name of the user + string LastName { get; set; } + /// User's phone number + string PhoneNumber { get; set; } + /// User's principal name + string Upn { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.json.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.json.cs new file mode 100644 index 00000000000..561483287c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/Models/UserDetails.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// User details for an organization + public partial class UserDetails + { + + /// + /// 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.NeonPostgres.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IUserDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json ? new UserDetails(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.NeonPostgres.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._firstName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._firstName.ToString()) : null, "firstName" ,container.Add ); + AddIf( null != (((object)this._lastName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._lastName.ToString()) : null, "lastName" ,container.Add ); + AddIf( null != (((object)this._emailAddress)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._emailAddress.ToString()) : null, "emailAddress" ,container.Add ); + AddIf( null != (((object)this._upn)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._upn.ToString()) : null, "upn" ,container.Add ); + AddIf( null != (((object)this._phoneNumber)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonString(this._phoneNumber.ToString()) : null, "phoneNumber" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject instance to deserialize from. + internal UserDetails(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_firstName = If( json?.PropertyT("firstName"), out var __jsonFirstName) ? (string)__jsonFirstName : (string)_firstName;} + {_lastName = If( json?.PropertyT("lastName"), out var __jsonLastName) ? (string)__jsonLastName : (string)_lastName;} + {_emailAddress = If( json?.PropertyT("emailAddress"), out var __jsonEmailAddress) ? (string)__jsonEmailAddress : (string)_emailAddress;} + {_upn = If( json?.PropertyT("upn"), out var __jsonUpn) ? (string)__jsonUpn : (string)_upn;} + {_phoneNumber = If( json?.PropertyT("phoneNumber"), out var __jsonPhoneNumber) ? (string)__jsonPhoneNumber : (string)_phoneNumber;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/NeonPostgres.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/NeonPostgres.cs new file mode 100644 index 00000000000..1b8c2d9ce8b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/api/NeonPostgres.cs @@ -0,0 +1,2771 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + + /// + /// Low-level API implementation for the Neon.Postgres service. + /// + public partial class NeonPostgres + { + + /// List the operations for the 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.NeonPostgres.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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Neon.Postgres/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the 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.NeonPostgres.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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Neon.Postgres/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Neon.Postgres/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the provider + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Neon.Postgres/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Neon.Postgres/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// List the operations for the provider + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListWithResult(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Neon.Postgres/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Resource create parameters. + /// 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.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// Resource create parameters. + /// 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.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Json string supplied to the OrganizationsCreateOrUpdate operation + /// 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.NeonPostgres.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 OrganizationsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Json string supplied to the OrganizationsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.NeonPostgres.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsCreateOrUpdate_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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.NeonPostgres.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Resource create parameters. + /// 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 OrganizationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.NeonPostgres.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 OrganizationsDelete(string subscriptionId, string resourceGroupName, string organizationName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a OrganizationResource + /// + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.NeonPostgres.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 OrganizationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.NeonPostgres.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 OrganizationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.NeonPostgres.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations 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 OrganizationsDelete_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + } + } + + /// Get a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations 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.NeonPostgres.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 OrganizationsGet(string subscriptionId, string resourceGroupName, string organizationName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a OrganizationResource + /// + /// 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.NeonPostgres.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 OrganizationsGetViaIdentity(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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a OrganizationResource + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsGetWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsGet_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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations 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 OrganizationsGet_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + } + } + + /// List OrganizationResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// 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.NeonPostgres.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 OrganizationsListByResourceGroup(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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by 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.NeonPostgres.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 OrganizationsListByResourceGroupViaIdentity(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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations$", 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/Neon.Postgres/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by resource group + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations$", 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/Neon.Postgres/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// List OrganizationResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListByResourceGroup_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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// 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 OrganizationsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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\._\(\)]+$"); + } + } + + /// List OrganizationResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// 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.NeonPostgres.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 OrganizationsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// + /// 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.NeonPostgres.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 OrganizationsListBySubscriptionViaIdentity(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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Neon.Postgres/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Neon.Postgres/organizations'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// List OrganizationResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Neon.Postgres/organizations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsListBySubscription_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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// 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 OrganizationsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// The resource properties to be updated. + /// 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.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// The resource properties to be updated. + /// 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.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-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/Neon.Postgres/organizations/(?[^/]+)$", 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/Neon.Postgres/organizations/{organizationName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var organizationName = _match.Groups["organizationName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Neon.Postgres/organizations/" + + organizationName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Json string supplied to the OrganizationsUpdate operation + /// 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.NeonPostgres.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 OrganizationsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OrganizationsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// Json string supplied to the OrganizationsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string organizationName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a OrganizationResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OrganizationsUpdateWithResult(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-08-01-preview"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Neon.Postgres/organizations/" + + global::System.Uri.EscapeDataString(organizationName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OrganizationsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.NeonPostgres.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 OrganizationsUpdate_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.NeonPostgres.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.NeonPostgres.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the Neon Organizations resource + /// The resource properties to be updated. + /// 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 OrganizationsUpdate_Validate(string subscriptionId, string resourceGroupName, string organizationName, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource body, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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(organizationName),organizationName); + await eventListener.AssertMinimumLength(nameof(organizationName),organizationName,1); + await eventListener.AssertMaximumLength(nameof(organizationName),organizationName,50); + await eventListener.AssertRegEx(nameof(organizationName), organizationName, @"^[a-zA-Z0-9][a-zA-Z0-9_\-.: ]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOperation_List.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOperation_List.cs new file mode 100644 index 00000000000..1ec36d4a6c5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOperation_List.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Neon.Postgres/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzNeonPostgresOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/providers/Neon.Postgres/operations", ApiVersion = "2024-08-01-preview")] + public partial class GetAzNeonPostgresOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzNeonPostgresOperation_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.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOperationListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_Get.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_Get.cs new file mode 100644 index 00000000000..f1f218e6c52 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_Get.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// Get a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzNeonPostgresOrganization_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"Get a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class GetAzNeonPostgresOrganization_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzNeonPostgresOrganization_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.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_GetViaIdentity.cs new file mode 100644 index 00000000000..8f7e17f1f51 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_GetViaIdentity.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// Get a OrganizationResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzNeonPostgresOrganization_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"Get a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class GetAzNeonPostgresOrganization_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity 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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzNeonPostgresOrganization_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.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsGetViaIdentity(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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List.cs new file mode 100644 index 00000000000..5fe0658020b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List.cs @@ -0,0 +1,518 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// List OrganizationResource resources by resource group + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzNeonPostgresOrganization_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"List OrganizationResource resources by resource group")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations", ApiVersion = "2024-08-01-preview")] + public partial class GetAzNeonPostgresOrganization_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzNeonPostgresOrganization_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.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult + /// 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.NeonPostgres.Models.IOrganizationResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List1.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List1.cs new file mode 100644 index 00000000000..fc55731fd7c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/GetAzNeonPostgresOrganization_List1.cs @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// List OrganizationResource resources by subscription ID + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Neon.Postgres/organizations" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzNeonPostgresOrganization_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"List OrganizationResource resources by subscription ID")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Neon.Postgres/organizations", ApiVersion = "2024-08-01-preview")] + public partial class GetAzNeonPostgresOrganization_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzNeonPostgresOrganization_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.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResourceListResult + /// 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.NeonPostgres.Models.IOrganizationResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateExpanded.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateExpanded.cs new file mode 100644 index 00000000000..60e2d7e85ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateExpanded.cs @@ -0,0 +1,893 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzNeonPostgresOrganization_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class NewAzNeonPostgresOrganization_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Neon + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// Business phone number of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Business phone number of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailBusinessPhone { get => _resourceBody.CompanyDetailBusinessPhone ?? null; set => _resourceBody.CompanyDetailBusinessPhone = value; } + + /// Company name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Company name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCompanyName { get => _resourceBody.CompanyDetailCompanyName ?? null; set => _resourceBody.CompanyDetailCompanyName = value; } + + /// Country name of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Country name of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCountry { get => _resourceBody.CompanyDetailCountry ?? null; set => _resourceBody.CompanyDetailCountry = value; } + + /// Domain of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Domain of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailDomain { get => _resourceBody.CompanyDetailDomain ?? null; set => _resourceBody.CompanyDetailDomain = value; } + + /// Number of employees in the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Number of employees in the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + public long CompanyDetailNumberOfEmployee { get => _resourceBody.CompanyDetailNumberOfEmployee ?? default(long); set => _resourceBody.CompanyDetailNumberOfEmployee = value; } + + /// Office address of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Office address of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailOfficeAddress { get => _resourceBody.CompanyDetailOfficeAddress ?? null; set => _resourceBody.CompanyDetailOfficeAddress = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// SaaS subscription id for the the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SaaS subscription id for the the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailSubscriptionId { get => _resourceBody.MarketplaceDetailSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceDetailSubscriptionStatus { get => _resourceBody.MarketplaceDetailSubscriptionStatus ?? null; set => _resourceBody.MarketplaceDetailSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Term Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Term Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmailAddress { get => _resourceBody.UserDetailEmailAddress ?? null; set => _resourceBody.UserDetailEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailFirstName { get => _resourceBody.UserDetailFirstName ?? null; set => _resourceBody.UserDetailFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailLastName { get => _resourceBody.UserDetailLastName ?? null; set => _resourceBody.UserDetailLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailPhoneNumber { get => _resourceBody.UserDetailPhoneNumber ?? null; set => _resourceBody.UserDetailPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailUpn { get => _resourceBody.UserDetailUpn ?? null; set => _resourceBody.UserDetailUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzNeonPostgresOrganization_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.NewAzNeonPostgresOrganization_CreateExpanded Clone() + { + var clone = new NewAzNeonPostgresOrganization_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._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzNeonPostgresOrganization_CreateExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..34375bfd783 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaIdentityExpanded.cs @@ -0,0 +1,870 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzNeonPostgresOrganization_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class NewAzNeonPostgresOrganization_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Neon + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// Business phone number of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Business phone number of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailBusinessPhone { get => _resourceBody.CompanyDetailBusinessPhone ?? null; set => _resourceBody.CompanyDetailBusinessPhone = value; } + + /// Company name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Company name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCompanyName { get => _resourceBody.CompanyDetailCompanyName ?? null; set => _resourceBody.CompanyDetailCompanyName = value; } + + /// Country name of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Country name of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCountry { get => _resourceBody.CompanyDetailCountry ?? null; set => _resourceBody.CompanyDetailCountry = value; } + + /// Domain of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Domain of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailDomain { get => _resourceBody.CompanyDetailDomain ?? null; set => _resourceBody.CompanyDetailDomain = value; } + + /// Number of employees in the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Number of employees in the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + public long CompanyDetailNumberOfEmployee { get => _resourceBody.CompanyDetailNumberOfEmployee ?? default(long); set => _resourceBody.CompanyDetailNumberOfEmployee = value; } + + /// Office address of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Office address of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailOfficeAddress { get => _resourceBody.CompanyDetailOfficeAddress ?? null; set => _resourceBody.CompanyDetailOfficeAddress = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity 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 = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// SaaS subscription id for the the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SaaS subscription id for the the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailSubscriptionId { get => _resourceBody.MarketplaceDetailSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceDetailSubscriptionStatus { get => _resourceBody.MarketplaceDetailSubscriptionStatus ?? null; set => _resourceBody.MarketplaceDetailSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Term Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Term Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmailAddress { get => _resourceBody.UserDetailEmailAddress ?? null; set => _resourceBody.UserDetailEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailFirstName { get => _resourceBody.UserDetailFirstName ?? null; set => _resourceBody.UserDetailFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailLastName { get => _resourceBody.UserDetailLastName ?? null; set => _resourceBody.UserDetailLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailPhoneNumber { get => _resourceBody.UserDetailPhoneNumber ?? null; set => _resourceBody.UserDetailPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailUpn { get => _resourceBody.UserDetailUpn ?? null; set => _resourceBody.UserDetailUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzNeonPostgresOrganization_CreateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.NewAzNeonPostgresOrganization_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzNeonPostgresOrganization_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzNeonPostgresOrganization_CreateViaIdentityExpanded() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate); + } + 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..dc575747e23 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonFilePath.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzNeonPostgresOrganization_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class NewAzNeonPostgresOrganization_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzNeonPostgresOrganization_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.NewAzNeonPostgresOrganization_CreateViaJsonFilePath Clone() + { + var clone = new NewAzNeonPostgresOrganization_CreateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzNeonPostgresOrganization_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonString.cs new file mode 100644 index 00000000000..e0921114a25 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/NewAzNeonPostgresOrganization_CreateViaJsonString.cs @@ -0,0 +1,603 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// create a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzNeonPostgresOrganization_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"create a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class NewAzNeonPostgresOrganization_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzNeonPostgresOrganization_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.NewAzNeonPostgresOrganization_CreateViaJsonString Clone() + { + var clone = new NewAzNeonPostgresOrganization_CreateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzNeonPostgresOrganization_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_Delete.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_Delete.cs new file mode 100644 index 00000000000..6e3e714e468 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_Delete.cs @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// Delete a OrganizationResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzNeonPostgresOrganization_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"Delete a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class RemoveAzNeonPostgresOrganization_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzNeonPostgresOrganization_Delete + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.RemoveAzNeonPostgresOrganization_Delete Clone() + { + var clone = new RemoveAzNeonPostgresOrganization_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzNeonPostgresOrganization_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 / application/json + 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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_DeleteViaIdentity.cs new file mode 100644 index 00000000000..51c53ed3230 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/RemoveAzNeonPostgresOrganization_DeleteViaIdentity.cs @@ -0,0 +1,586 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// Delete a OrganizationResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzNeonPostgresOrganization_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"Delete a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class RemoveAzNeonPostgresOrganization_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity 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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzNeonPostgresOrganization_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.RemoveAzNeonPostgresOrganization_DeleteViaIdentity Clone() + { + var clone = new RemoveAzNeonPostgresOrganization_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsDeleteViaIdentity(InputObject.Id, onNoContent, 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzNeonPostgresOrganization_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 / application/json + 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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateExpanded.cs new file mode 100644 index 00000000000..c8d161578fb --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateExpanded.cs @@ -0,0 +1,894 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzNeonPostgresOrganization_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class SetAzNeonPostgresOrganization_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Neon + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// Business phone number of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Business phone number of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailBusinessPhone { get => _resourceBody.CompanyDetailBusinessPhone ?? null; set => _resourceBody.CompanyDetailBusinessPhone = value; } + + /// Company name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Company name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCompanyName { get => _resourceBody.CompanyDetailCompanyName ?? null; set => _resourceBody.CompanyDetailCompanyName = value; } + + /// Country name of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Country name of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCountry { get => _resourceBody.CompanyDetailCountry ?? null; set => _resourceBody.CompanyDetailCountry = value; } + + /// Domain of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Domain of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailDomain { get => _resourceBody.CompanyDetailDomain ?? null; set => _resourceBody.CompanyDetailDomain = value; } + + /// Number of employees in the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Number of employees in the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + public long CompanyDetailNumberOfEmployee { get => _resourceBody.CompanyDetailNumberOfEmployee ?? default(long); set => _resourceBody.CompanyDetailNumberOfEmployee = value; } + + /// Office address of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Office address of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailOfficeAddress { get => _resourceBody.CompanyDetailOfficeAddress ?? null; set => _resourceBody.CompanyDetailOfficeAddress = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// SaaS subscription id for the the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "SaaS subscription id for the the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"SaaS subscription id for the the marketplace offer", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailSubscriptionId { get => _resourceBody.MarketplaceDetailSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailSubscriptionId = value; } + + /// Marketplace subscription status + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace subscription status")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace subscription status", + SerializedName = @"subscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + public string MarketplaceDetailSubscriptionStatus { get => _resourceBody.MarketplaceDetailSubscriptionStatus ?? null; set => _resourceBody.MarketplaceDetailSubscriptionStatus = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Offer Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id for the marketplace offer", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailOfferId { get => _resourceBody.OfferDetailOfferId ?? null; set => _resourceBody.OfferDetailOfferId = value; } + + /// Plan Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id for the marketplace offer", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanId { get => _resourceBody.OfferDetailPlanId ?? null; set => _resourceBody.OfferDetailPlanId = value; } + + /// Plan Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Name for the marketplace offer", + SerializedName = @"planName", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPlanName { get => _resourceBody.OfferDetailPlanName ?? null; set => _resourceBody.OfferDetailPlanName = value; } + + /// Publisher Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id for the marketplace offer", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailPublisherId { get => _resourceBody.OfferDetailPublisherId ?? null; set => _resourceBody.OfferDetailPublisherId = value; } + + /// Term Id for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Id for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Id for the marketplace offer", + SerializedName = @"termId", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermId { get => _resourceBody.OfferDetailTermId ?? null; set => _resourceBody.OfferDetailTermId = value; } + + /// Term Name for the marketplace offer + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Name for the marketplace offer")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Name for the marketplace offer", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string OfferDetailTermUnit { get => _resourceBody.OfferDetailTermUnit ?? null; set => _resourceBody.OfferDetailTermUnit = value; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _resourceBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _resourceBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _resourceBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _resourceBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _resourceBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _resourceBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _resourceBody.SingleSignOnPropertySingleSignOnState ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _resourceBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _resourceBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmailAddress { get => _resourceBody.UserDetailEmailAddress ?? null; set => _resourceBody.UserDetailEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailFirstName { get => _resourceBody.UserDetailFirstName ?? null; set => _resourceBody.UserDetailFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailLastName { get => _resourceBody.UserDetailLastName ?? null; set => _resourceBody.UserDetailLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailPhoneNumber { get => _resourceBody.UserDetailPhoneNumber ?? null; set => _resourceBody.UserDetailPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailUpn { get => _resourceBody.UserDetailUpn ?? null; set => _resourceBody.UserDetailUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzNeonPostgresOrganization_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.SetAzNeonPostgresOrganization_UpdateExpanded Clone() + { + var clone = new SetAzNeonPostgresOrganization_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzNeonPostgresOrganization_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..42f4d8c2c4a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs @@ -0,0 +1,606 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzNeonPostgresOrganization_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class SetAzNeonPostgresOrganization_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzNeonPostgresOrganization_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.SetAzNeonPostgresOrganization_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzNeonPostgresOrganization_UpdateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzNeonPostgresOrganization_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonString.cs new file mode 100644 index 00000000000..181e0989554 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/SetAzNeonPostgresOrganization_UpdateViaJsonString.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzNeonPostgresOrganization_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class SetAzNeonPostgresOrganization_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzNeonPostgresOrganization_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.SetAzNeonPostgresOrganization_UpdateViaJsonString Clone() + { + var clone = new SetAzNeonPostgresOrganization_UpdateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzNeonPostgresOrganization_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateExpanded.cs new file mode 100644 index 00000000000..3eb93429c19 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateExpanded.cs @@ -0,0 +1,793 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzNeonPostgresOrganization_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class UpdateAzNeonPostgresOrganization_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Neon + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// Business phone number of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Business phone number of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailBusinessPhone { get => _propertiesBody.CompanyDetailBusinessPhone ?? null; set => _propertiesBody.CompanyDetailBusinessPhone = value; } + + /// Company name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Company name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCompanyName { get => _propertiesBody.CompanyDetailCompanyName ?? null; set => _propertiesBody.CompanyDetailCompanyName = value; } + + /// Country name of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Country name of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCountry { get => _propertiesBody.CompanyDetailCountry ?? null; set => _propertiesBody.CompanyDetailCountry = value; } + + /// Domain of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Domain of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailDomain { get => _propertiesBody.CompanyDetailDomain ?? null; set => _propertiesBody.CompanyDetailDomain = value; } + + /// Number of employees in the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Number of employees in the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + public long CompanyDetailNumberOfEmployee { get => _propertiesBody.CompanyDetailNumberOfEmployee ?? default(long); set => _propertiesBody.CompanyDetailNumberOfEmployee = value; } + + /// Office address of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Office address of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailOfficeAddress { get => _propertiesBody.CompanyDetailOfficeAddress ?? null; set => _propertiesBody.CompanyDetailOfficeAddress = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _propertiesBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _propertiesBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _propertiesBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _propertiesBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _propertiesBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _propertiesBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _propertiesBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _propertiesBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _propertiesBody.SingleSignOnPropertySingleSignOnState ?? null; set => _propertiesBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _propertiesBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _propertiesBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => _propertiesBody.Tag ?? null /* object */; set => _propertiesBody.Tag = value; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmailAddress { get => _propertiesBody.UserDetailEmailAddress ?? null; set => _propertiesBody.UserDetailEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailFirstName { get => _propertiesBody.UserDetailFirstName ?? null; set => _propertiesBody.UserDetailFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailLastName { get => _propertiesBody.UserDetailLastName ?? null; set => _propertiesBody.UserDetailLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailPhoneNumber { get => _propertiesBody.UserDetailPhoneNumber ?? null; set => _propertiesBody.UserDetailPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailUpn { get => _propertiesBody.UserDetailUpn ?? null; set => _propertiesBody.UserDetailUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzNeonPostgresOrganization_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.UpdateAzNeonPostgresOrganization_UpdateExpanded Clone() + { + var clone = new UpdateAzNeonPostgresOrganization_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._propertiesBody = this._propertiesBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsUpdate(SubscriptionId, ResourceGroupName, Name, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzNeonPostgresOrganization_UpdateExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..46befd89a9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded.cs @@ -0,0 +1,772 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzNeonPostgresOrganization_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + public partial class UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// Organization Resource by Neon + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource _propertiesBody = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.OrganizationResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// Business phone number of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Business phone number of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Business phone number of the company", + SerializedName = @"businessPhone", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailBusinessPhone { get => _propertiesBody.CompanyDetailBusinessPhone ?? null; set => _propertiesBody.CompanyDetailBusinessPhone = value; } + + /// Company name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Company name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Company name", + SerializedName = @"companyName", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCompanyName { get => _propertiesBody.CompanyDetailCompanyName ?? null; set => _propertiesBody.CompanyDetailCompanyName = value; } + + /// Country name of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Country name of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Country name of the company", + SerializedName = @"country", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailCountry { get => _propertiesBody.CompanyDetailCountry ?? null; set => _propertiesBody.CompanyDetailCountry = value; } + + /// Domain of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Domain of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Domain of the user", + SerializedName = @"domain", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailDomain { get => _propertiesBody.CompanyDetailDomain ?? null; set => _propertiesBody.CompanyDetailDomain = value; } + + /// Number of employees in the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Number of employees in the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Number of employees in the company", + SerializedName = @"numberOfEmployees", + PossibleTypes = new [] { typeof(long) })] + public long CompanyDetailNumberOfEmployee { get => _propertiesBody.CompanyDetailNumberOfEmployee ?? default(long); set => _propertiesBody.CompanyDetailNumberOfEmployee = value; } + + /// Office address of the company + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Office address of the company")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Office address of the company", + SerializedName = @"officeAddress", + PossibleTypes = new [] { typeof(string) })] + public string CompanyDetailOfficeAddress { get => _propertiesBody.CompanyDetailOfficeAddress ?? null; set => _propertiesBody.CompanyDetailOfficeAddress = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.INeonPostgresIdentity 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.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// Organization Id in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization Id in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization Id in partner's system", + SerializedName = @"organizationId", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationId { get => _propertiesBody.PartnerOrganizationPropertyOrganizationId ?? null; set => _propertiesBody.PartnerOrganizationPropertyOrganizationId = value; } + + /// Organization name in partner's system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Organization name in partner's system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Organization name in partner's system", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + public string PartnerOrganizationPropertyOrganizationName { get => _propertiesBody.PartnerOrganizationPropertyOrganizationName ?? null; set => _propertiesBody.PartnerOrganizationPropertyOrganizationName = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// List of AAD domains fetched from Microsoft Graph for user. + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "List of AAD domains fetched from Microsoft Graph for user.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"List of AAD domains fetched from Microsoft Graph for user.", + SerializedName = @"aadDomains", + PossibleTypes = new [] { typeof(string) })] + public string[] SingleSignOnPropertyAadDomain { get => _propertiesBody.SingleSignOnPropertyAadDomain?.ToArray() ?? null /* fixedArrayOf */; set => _propertiesBody.SingleSignOnPropertyAadDomain = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// AAD enterprise application Id used to setup SSO + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "AAD enterprise application Id used to setup SSO")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"AAD enterprise application Id used to setup SSO", + SerializedName = @"enterpriseAppId", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertyEnterpriseAppId { get => _propertiesBody.SingleSignOnPropertyEnterpriseAppId ?? null; set => _propertiesBody.SingleSignOnPropertyEnterpriseAppId = value; } + + /// State of the Single Sign On for the organization + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "State of the Single Sign On for the organization")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"State of the Single Sign On for the organization", + SerializedName = @"singleSignOnState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.PSArgumentCompleterAttribute("Initial", "Enable", "Disable")] + public string SingleSignOnPropertySingleSignOnState { get => _propertiesBody.SingleSignOnPropertySingleSignOnState ?? null; set => _propertiesBody.SingleSignOnPropertySingleSignOnState = value; } + + /// URL for SSO to be used by the partner to redirect the user to their system + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "URL for SSO to be used by the partner to redirect the user to their system")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"URL for SSO to be used by the partner to redirect the user to their system", + SerializedName = @"singleSignOnUrl", + PossibleTypes = new [] { typeof(string) })] + public string SingleSignOnPropertySingleSignOnUrl { get => _propertiesBody.SingleSignOnPropertySingleSignOnUrl ?? null; set => _propertiesBody.SingleSignOnPropertySingleSignOnUrl = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.ITags Tag { get => _propertiesBody.Tag ?? null /* object */; set => _propertiesBody.Tag = value; } + + /// Email address of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Email address of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Email address of the user", + SerializedName = @"emailAddress", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmailAddress { get => _propertiesBody.UserDetailEmailAddress ?? null; set => _propertiesBody.UserDetailEmailAddress = value; } + + /// First name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "First name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"First name of the user", + SerializedName = @"firstName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailFirstName { get => _propertiesBody.UserDetailFirstName ?? null; set => _propertiesBody.UserDetailFirstName = value; } + + /// Last name of the user + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Last name of the user")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Last name of the user", + SerializedName = @"lastName", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailLastName { get => _propertiesBody.UserDetailLastName ?? null; set => _propertiesBody.UserDetailLastName = value; } + + /// User's phone number + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's phone number")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's phone number", + SerializedName = @"phoneNumber", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailPhoneNumber { get => _propertiesBody.UserDetailPhoneNumber ?? null; set => _propertiesBody.UserDetailPhoneNumber = value; } + + /// User's principal name + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User's principal name")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User's principal name", + SerializedName = @"upn", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailUpn { get => _propertiesBody.UserDetailUpn ?? null; set => _propertiesBody.UserDetailUpn = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// + /// a duplicate instance of UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._propertiesBody = this._propertiesBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.OrganizationsUpdateViaIdentity(InputObject.Id, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate); + } + 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.OrganizationName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.OrganizationName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.OrganizationsUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.OrganizationName ?? null, _propertiesBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzNeonPostgresOrganization_UpdateViaIdentityExpanded() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..83b5e8dbb49 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzNeonPostgresOrganization_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath Clone() + { + var clone = new UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzNeonPostgresOrganization_UpdateViaJsonFilePath() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonString.cs new file mode 100644 index 00000000000..4b6e13a1baf --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/cmdlets/UpdateAzNeonPostgresOrganization_UpdateViaJsonString.cs @@ -0,0 +1,603 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets; + using System; + + /// update a OrganizationResource + /// + /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzNeonPostgresOrganization_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Description(@"update a OrganizationResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Neon.Postgres/organizations/{organizationName}", ApiVersion = "2024-08-01-preview")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NotSuggestDefaultParameterSet] + public partial class UpdateAzNeonPostgresOrganization_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the Neon Organizations resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the Neon Organizations resource")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the Neon Organizations resource", + SerializedName = @"organizationName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("OrganizationName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Category(global::Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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 Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzNeonPostgresOrganization_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Cmdlets.UpdateAzNeonPostgresOrganization_UpdateViaJsonString Clone() + { + var clone = new UpdateAzNeonPostgresOrganization_UpdateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.NeonPostgres.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'OrganizationsUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OrganizationsUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzNeonPostgresOrganization_UpdateViaJsonString() + { + + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Models.IOrganizationResource + /// 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.NeonPostgres.Models.IOrganizationResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..cce6eb2ebcc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this cmdlet"); + } + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..9e04a03ed27 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..7cf3fa929b9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to a type + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..5f5c997e588 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..781d26f833f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..94a0eecd88a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..4e940c4caa8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..e214bab345d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..35fbd015ede --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..276d9d43c81 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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.NeonPostgres.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..7142b68af20 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.HasAllowEmptyArray.ToAllowEmptyArray()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..26f7a887dfc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.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.NeonPostgres.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: NeonPostgres cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.NeonPostgres.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.NeonPostgres.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = '{previewVersion}'"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule Sphere".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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..6b5f7f1fb53 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + /*var loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + + + + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + sb.AppendLine(@"{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath)" + ); + sb.AppendLine($@" $TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@" $currentPath = $PSScriptRoot + while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent + } + . ($mockingPath | Select-Object -First 1).FullName +} +"); + + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..a83f9df7df7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..0766e1227fd --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..50aa33e0186 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..924f1ab75df --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..38b7bbc7fe2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"[{relatedLink}]({relatedLink}){Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..444dbbee9f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..7b916fb9549 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + ExampleInfo.Description.ToDescriptionFormat()); ; + } + } + } + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://learn.microsoft.com/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Synopsis.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + public const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..3029347b36b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..8f4620eebc4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && !pg.Parameters.All(p => p.IsHidden())) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (codeEndIndex ?? 0)) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, output, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow && !p.IsHidden()).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..bc755f7c8ae --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{Environment.NewLine}" : String.Empty; + } + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText}{externalUrlsText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new[] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new[] { "
", "\r\n", "\n" }); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..b6e578db66a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + + public string RootModuleName { get => @""; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + if (variantParamCountGroups.Length == 0) + { + variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + } + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public bool IsNotSuggestDefaultParameterSet { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + IsNotSuggestDefaultParameterSet = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public bool HasAllowEmptyArray { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + public PSArgumentCompleterAttribute PSArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}"; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines(); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[] { } : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => (!ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + public static PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(completerAttribute); + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..0737a8cae7e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class ConstantAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..1f21ded8a88 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..159a2223b04 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,105 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.TrimStart().StartsWith(GuidStart.TrimStart()))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..accb4392d8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..2b69d09e76e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..f940bc72f42 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..8935ee6a221 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.NeonPostgres Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..b4c76d836d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..0901a6df864 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..0db901e4ee8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..fb5413832a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..f7a84d6409d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..1a8f51a991e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..2970e42f50a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..3e6631bfaa1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..dbcdc2cbc9d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..cc7ec574f3d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..4a0f59b9ee6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..f294d14c49f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..eb75d2eb6a6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..516fe0cd73a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..d970e1ba5ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..d4b0bc00bfa --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..e15884d893c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..1ece02a0430 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..49b12778363 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..22ed6afeee3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..145087506ba --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..1e9317b28c2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..16b9792f401 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..a56a498e874 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..b9583c0efe0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..a5e3fb28315 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..ecf9ac4fa95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..4ebc6cca12e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.JsonSerializable.ToJson(dict, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..881d3b93598 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..05b43b7b093 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..3b92744ae8b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..34b510f3866 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..11f34945220 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..98e3161648f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..63ccba98dfb --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..1d2b4a3eff7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..0a5e21319d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..b1d36a3fcde --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..211312ac3cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime +{ + using System; + + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..cdc311a5d78 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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.NeonPostgres.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..0c554eecfcf --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + public const string Progress = nameof(Progress); + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..c5c7add500e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..cae8425fdd1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Extensions.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..9934de037b1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..c01a89dc6b0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..401812c78e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..895099297d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..b6eb273a919 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..19bdbe09d60 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..50c58f4b65e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..cb12b6d901a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..0625738ddcb --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..d6d83187425 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/ISendAsync.cs @@ -0,0 +1,413 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private const int DefaultMaxRetry = 3; + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..a683f23b47c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..da70809f031 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..c7f34fb78e0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..fb8e8114769 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..d8e693b7c64 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..6e9480f447e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..943884d1aec --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..b591df27c26 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..cd083502a39 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..141b578276d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..9b7eb152444 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..75eda0e0339 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..b70761f4597 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..40444474ac0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + internal XNodeArray(System.Collections.Generic.List values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..4fab012b88f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..84fab39ec93 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..1838303365d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..06e7343607d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..563db07bb65 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..66f30fdee2b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..a287e89efdb --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..9e9fd6a7c3b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..3329a4abeb2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..758346a1fdd --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..a9224c15efe --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..91b6921e5a2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..f2fde4d7071 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..2d3a8c1515a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..7f113fd0475 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..85f4b86ec60 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..b5d6c8922fc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"), isBase64Request)) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..237903623ac --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..a08a2e50172 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..8912b4136d7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..9472cee8b0e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..7b75fab264d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..4b196f8e642 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..dba0c2bf9cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/SerializationMode.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..3a62eccb83d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.List SelectToList(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }.ToList(); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0].ToList(); // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result; + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..3fd1b489b8c --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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.NeonPostgres.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // see if there is an error block in the body + json = json?.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..0392b75f95d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..0e581433a9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/how-to.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/how-to.md new file mode 100644 index 00000000000..24f3241cdfe --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.NeonPostgres`. + +## Building `Az.NeonPostgres` +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.NeonPostgres` +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.NeonPostgres` +To pack `Az.NeonPostgres` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.NeonPostgres`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.NeonPostgres.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.NeonPostgres.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.NeonPostgres`. + - `-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.NeonPostgres` 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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/Az.NeonPostgres.internal.psm1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/Az.NeonPostgres.internal.psm1 new file mode 100644 index 00000000000..a52efa7e1d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/Az.NeonPostgres.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.NeonPostgres.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/README.md new file mode 100644 index 00000000000..23d06426e3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/internal/README.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.NeonPostgres.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.NeonPostgres`. Instead, this sub-module is imported by the `..\custom\Az.NeonPostgres.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.NeonPostgres.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.NeonPostgres`. diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/license.txt b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/license.txt @@ -0,0 +1,227 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + + +The software includes the AutoMapper library ("AutoMapper"). The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Provided for Informational Purposes Only + +AutoMapper + +The MIT License (MIT) +Copyright (c) 2010 Jimmy Bogard + + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + +*************** + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/resources/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/run-module.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/run-module.ps1 new file mode 100644 index 00000000000..d68bc8634e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.NeonPostgres.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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test-module.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test-module.ps1 new file mode 100644 index 00000000000..ea80248ffd3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) +{ + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.NeonPostgres.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/README.md new file mode 100644 index 00000000000..cdaf3a995a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/README.md @@ -0,0 +1,438 @@ + +# Az.Resources.TestSupport +This directory contains the PowerShell module for the Resources service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Resources.TestSupport`, 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
`npm install -g 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` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +> Values +``` yaml +azure: true +powershell: true +branch: master +repo: https://github.com/Azure/azure-rest-api-specs/blob/$(branch) +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + copyright: Microsoft Corporation. All rights reserved. + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell +``` + +> Names +``` yaml +prefix: Az +``` + +> Folders +``` yaml +clear-output-folder: true +``` + +``` yaml +input-file: + - $(repo)/specification/resources/resource-manager/Microsoft.Resources/stable/2018-05-01/resources.json +module-name: Az.Resources.TestSupport +namespace: Microsoft.Azure.PowerShell.Cmdlets.Resources + +subject-prefix: '' +module-version: 0.0.1 +title: Resources + +directive: + - remove-operation: Deployments_CreateOrUpdateAtSubscriptionScope + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - from: swagger-document + where: $..parameters[?(@.name=='$filter')] + transform: $['x-ms-skip-url-encoding'] = true + - from: swagger-document + where: $..[?( /Resources_(CreateOrUpdate|Update|Delete|Get|GetById|CheckExistence|CheckExistenceById)/g.exec(@.operationId))] + transform: "$.parameters = $.parameters.map( each => { each.name = each.name === 'api-version' ? 'explicit-api-version' : each.name; return each; } );" + - from: source-file-csharp + where: $ + transform: $ = $.replace(/explicit-api-version/g, 'api-version'); + - where: + parameter-name: ExplicitApiVersion + set: + parameter-name: ApiVersion + - from: source-file-csharp + where: $ + transform: > + $ = $.replace(/result.OdataNextLink/g,'nextLink' ); + return $.replace( /(^\s*)(if\s*\(\s*nextLink\s*!=\s*null\s*\))/gm, '$1var nextLink = Module.Instance.FixNextLink(responseMessage, result.OdataNextLink);\n$1$2' ); + - from: swagger-document + where: + - $..DeploymentProperties.properties.template + - $..DeploymentProperties.properties.parameters + - $..ResourceGroupExportResult.properties.template + - $..PolicyDefinitionProperties.properties.policyRule + transform: $.additionalProperties = true; + - where: + verb: Set + subject: Resource + remove: true + - where: + verb: Set + subject: Deployment + remove: true + - where: + subject: Resource + parameter-name: GroupName + set: + parameter-name: ResourceGroupName + clear-alias: true + - where: + subject: Resource + parameter-name: Id + set: + parameter-name: ResourceId + clear-alias: true + - where: + subject: Resource + parameter-name: Type + set: + parameter-name: ResourceType + clear-alias: true + - where: + subject: Appliance* + remove: true + - where: + verb: Test + subject: CheckNameAvailability + set: + subject: NameAvailability + - where: + verb: Export + subject: ResourceGroupTemplate + set: + subject: ResourceGroup + alias: Export-AzResourceGroupTemplate + - where: + parameter-name: Filter + set: + alias: ODataQuery + - where: + verb: Test + subject: ResourceGroupExistence + set: + subject: ResourceGroup + alias: Test-AzResourceGroupExistence + - where: + verb: Export + subject: DeploymentTemplate + set: + alias: [Save-AzDeploymentTemplate, Save-AzResourceGroupDeploymentTemplate] + - where: + subject: Deployment + set: + alias: ${verb}-AzResourceGroupDeployment + - where: + verb: Get + subject: DeploymentOperation + set: + alias: Get-AzResourceGroupDeploymentOperation + - where: + verb: New + subject: Deployment + variant: Create.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + hide: true + - where: + verb: Test + subject: Deployment + variant: Validate.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + parameter-name: DebugSettingDetailLevel + set: + parameter-name: DeploymentDebugLogLevel + - where: + subject: Provider + set: + subject: ResourceProvider + - where: + subject: ProviderFeature|ResourceProvider|ResourceLock + parameter-name: ResourceProviderNamespace + set: + alias: ProviderNamespace + - where: + verb: Update + subject: ResourceGroup + parameter-name: Name + clear-alias: true + - where: + parameter-name: UpnOrObjectId + set: + alias: ['UserPrincipalName', 'Upn', 'ObjectId'] + - where: + subject: Deployment + variant: (.*)Expanded(.*) + parameter-name: Parameter + set: + parameter-name: DeploymentParameter + # Format output + - where: + model-name: GenericResource + set: + format-table: + properties: + - Name + - ResourceGroupName + - Type + - Location + labels: + Type: ResourceType + - where: + model-name: ResourceGroup + set: + format-table: + properties: + - Name + - Location + - ProvisioningState + - where: + model-name: DeploymentExtended + set: + format-table: + properties: + - Name + - ProvisioningState + - Timestamp + - Mode + - where: + model-name: PolicyAssignment + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicyDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicySetDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: Provider + set: + format-table: + properties: + - Namespace + - RegistrationState + - where: + model-name: ProviderResourceType + set: + format-table: + properties: + - ResourceType + - Location + - ApiVersion + - where: + model-name: FeatureResult + set: + format-table: + properties: + - Name + - State + - where: + model-name: TagDetails + set: + format-table: + properties: + - TagName + - CountValue + - where: + model-name: Application + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppId + - Homepage + - AvailableToOtherTenant + - where: + model-name: KeyCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - Type + - where: + model-name: PasswordCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - where: + model-name: User + set: + format-table: + properties: + - PrincipalName + - DisplayName + - ObjectId + - Type + - where: + model-name: AdGroup + set: + format-table: + properties: + - DisplayName + - Mail + - ObjectId + - SecurityEnabled + - where: + model-name: ServicePrincipal + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppDisplayName + - AppId + - where: + model-name: Location + set: + format-table: + properties: + - Name + - DisplayName + - where: + model-name: ManagementLockObject + set: + format-table: + properties: + - Name + - Level + - ResourceId + - where: + model-name: RoleAssignment + set: + format-table: + properties: + - DisplayName + - ObjectId + - ObjectType + - RoleDefinitionName + - Scope + - where: + model-name: RoleDefinition + set: + format-table: + properties: + - RoleName + - Name + - Action +# To remove cmdlets not used in the test frame + - where: + subject: Operation + remove: true + - where: + subject: Deployment + variant: (.*)1|Cancel(.*)|Validate(.*)|Export(.*)|List(.*)|Delete(.*)|Check(.*)|Calculate(.*) + remove: true + - where: + subject: ResourceProvider + variant: Register(.*)|Unregister(.*)|Get(.*) + remove: true + - where: + subject: ResourceGroup + variant: List(.*)|Update(.*)|Export(.*)|Move(.*) + remove: true + - where: + subject: Resource + remove: true + - where: + subject: Tag|TagValue + remove: true + - where: + subject: DeploymentOperation + remove: true + - where: + subject: DeploymentTemplate + remove: true + - where: + subject: Calculate(.*) + remove: true + - where: + subject: ResourceExistence + remove: true + - where: + subject: ResourceMoveResource + remove: true + - where: + subject: DeploymentExistence + remove: true +``` diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/custom/New-AzDeployment.ps1 @@ -0,0 +1,231 @@ +function New-AzDeployment { + [OutputType('Microsoft.Azure.PowerShell.Cmdlets.Resources.Models.IDeploymentExtended')] + [CmdletBinding(DefaultParameterSetName='CreateWithTemplateFileParameterFile', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Description('You can provide the template and parameters directly in the request or link to JSON files.')] + param( + [Parameter(HelpMessage='The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name.')] + [Alias('DeploymentName')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='deploymentName', Required, PossibleTypes=([System.String]), Description='The name of the deployment.')] + [System.String] + # The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name. + ${Name}, + + [Parameter(Mandatory, HelpMessage='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='subscriptionId', Required, PossibleTypes=([System.String]), Description='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='resourceGroupName', Required, PossibleTypes=([System.String]), Description='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [System.String] + # The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [System.String] + # Local path to the JSON template file. + ${TemplateFile}, + + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [System.String] + # The string representation of the JSON template. + ${TemplateJson}, + + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the JSON template. + ${TemplateObject}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [System.String] + # Local path to the parameter JSON template file. + ${TemplateParameterFile}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [System.String] + # The string representation of the parameter JSON template. + ${TemplateParameterJson}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the parameter JSON template. + ${TemplateParameterObject}, + + [Parameter(Mandatory, HelpMessage='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode])] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='mode', Required, PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode]), Description='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode] + # The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. + ${Mode}, + + [Parameter(HelpMessage='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='detailLevel', PossibleTypes=([System.String]), Description='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [System.String] + # Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations. + ${DeploymentDebugLogLevel}, + + [Parameter(HelpMessage='The location to store the deployment data.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='location', PossibleTypes=([System.String]), Description='The location to store the deployment data.')] + [System.String] + # The location to store the deployment data. + ${Location}, + + [Parameter(HelpMessage='The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(HelpMessage='Run the command asynchronously')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait} + + ) + + process { + if ($PSBoundParameters.ContainsKey("TemplateFile")) + { + if (!(Test-Path -Path $TemplateFile)) + { + throw "Unable to find template file '$TemplateFile'." + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (Get-Item -Path $TemplateFile).BaseName + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + $TemplateJson = [System.IO.File]::ReadAllText($TemplateFile) + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateJson")) + { + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateObject")) + { + $TemplateJson = ConvertTo-Json -InputObject $TemplateObject + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateObject") + } + + if ($PSBoundParameters.ContainsKey("TemplateParameterFile")) + { + if (!(Test-Path -Path $TemplateParameterFile)) + { + throw "Unable to find template parameter file '$TemplateParameterFile'." + } + + $ParameterJson = [System.IO.File]::ReadAllText($TemplateParameterFile) + $ParameterObject = ConvertFrom-Json -InputObject $ParameterJson + $ParameterHashtable = @{} + $ParameterObject.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + $ParameterHashtable.Remove("`$schema") + $ParameterHashtable.Remove("contentVersion") + $NestedValues = $ParameterHashtable.parameters + if ($null -ne $NestedValues) + { + $ParameterHashtable.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + } + + $ParameterJson = ConvertTo-Json -InputObject $ParameterHashtable + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $ParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterJson")) + { + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterObject")) + { + $TemplateParameterObject.Remove("`$schema") + $TemplateParameterObject.Remove("contentVersion") + $NestedValues = $TemplateParameterObject.parameters + if ($null -ne $NestedValues) + { + $TemplateParameterObject.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $TemplateParameterObject[$_.Name] = $_.Value } + } + + $TemplateParameterJson = ConvertTo-Json -InputObject $TemplateParameterObject + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterObject") + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (New-Guid).Guid + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + if ($PSBoundParameters.ContainsKey("ResourceGroupName")) + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + else + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Resources` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overriden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Resources` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/how-to.md @@ -0,0 +1,60 @@ +# How-To +This document describes how to develop for `Az.Resources`. + +## Building `Az.Resources` +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.Resources` +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.Resources` +To pack `Az.Resources` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Resources`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Resources.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Resources.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Resources`. + - `-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.Resources` 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`. +- `generate-portal-ux.ps1` + - Generates a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +- `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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/license.txt @@ -0,0 +1,203 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md @@ -0,0 +1,598 @@ +### AzADApplication [Get, New, Remove, Update] `IApplication, Boolean` + - TenantId `String` + - ObjectId `String` + - IncludeDeleted `SwitchParameter` + - InputObject `IResourcesIdentity` + - HardDelete `SwitchParameter` + - Filter `String` + - IdentifierUri `String` + - DisplayNameStartWith `String` + - DisplayName `String` + - ApplicationId `String` + - AllowGuestsSignIn `SwitchParameter` + - AllowPassthroughUser `SwitchParameter` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenants `SwitchParameter` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes` + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `SwitchParameter` + - Oauth2AllowUrlPathMatching `SwitchParameter` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `SwitchParameter` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `SwitchParameter` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + - Parameter `IApplicationCreateParameters` + - PassThru `SwitchParameter` + - AvailableToOtherTenant `SwitchParameter` + +### AzADApplicationOwner [Add, Get, Remove] `Boolean, IDirectoryObject` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADDeletedApplication [Restore] `IApplication` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + +### AzADGroup [Get, New, Remove] `IAdGroup, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayNameStartsWith `String` + - DisplayName `String` + - AdditionalProperties `Hashtable` + - MailNickname `String` + - Parameter `IGroupCreateParameters` + - PassThru `SwitchParameter` + +### AzADGroupMember [Add, Get, Remove, Test] `Boolean, IDirectoryObject, SwitchParameter` + - GroupObjectId `String` + - TenantId `String` + - MemberObjectId `String[]` + - MemberUserPrincipalName `String[]` + - GroupObject `IAdGroup` + - GroupDisplayName `String` + - InputObject `IResourcesIdentity` + - ObjectId `String` + - ShowOwner `SwitchParameter` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IGroupAddMemberParameters` + - DisplayName `String` + - GroupId `String` + - MemberId `String` + +### AzADGroupMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IGroupGetMemberGroupsParameters` + +### AzADGroupOwner [Add, Remove] `Boolean` + - ObjectId `String` + - TenantId `String` + - GroupObjectId `String` + - MemberObjectId `String[]` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADObject [Get] `IDirectoryObject` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - IncludeDirectoryObjectReference `SwitchParameter` + - ObjectId `String[]` + - Type `String[]` + - Parameter `IGetObjectsParameters` + +### AzADServicePrincipal [Get, New, Remove, Update] `IServicePrincipal, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ApplicationObject `IApplication` + - ServicePrincipalName `String` + - DisplayNameBeginsWith `String` + - DisplayName `String` + - ApplicationId `String` + - AccountEnabled `SwitchParameter` + - AppId `String` + - AppRoleAssignmentRequired `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + - Parameter `IServicePrincipalCreateParameters` + - PassThru `SwitchParameter` + +### AzADServicePrincipalOwner [Get] `IDirectoryObject` + - ObjectId `String` + - TenantId `String` + +### AzADUser [Get, New, Remove, Update] `IUser, Boolean` + - TenantId `String` + - UpnOrObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayName `String` + - StartsWith `String` + - Mail `String` + - MailNickname `String` + - Parameter `IUserCreateParameters` + - AccountEnabled `SwitchParameter` + - GivenName `String` + - ImmutableId `String` + - PasswordProfile `IPasswordProfile` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType` + - PassThru `SwitchParameter` + - EnableAccount `SwitchParameter` + +### AzADUserMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IUserGetMemberGroupsParameters` + +### AzApplicationKeyCredentials [Get, Update] `IKeyCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IKeyCredentialsUpdateParameters` + - Value `IKeyCredential[]` + +### AzApplicationPasswordCredentials [Get, Update] `IPasswordCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IPasswordCredentialsUpdateParameters` + - Value `IPasswordCredential[]` + +### AzAuthorizationOperation [Get] `IOperation` + +### AzClassicAdministrator [Get] `IClassicAdministrator` + - SubscriptionId `String[]` + +### AzDenyAssignment [Get] `IDenyAssignment` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - Filter `String` + +### AzDeployment [Get, New, Remove, Set, Stop, Test] `IDeploymentExtended, Boolean, IDeploymentValidateResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Top `Int32` + - Parameter `IDeployment` + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - PassThru `SwitchParameter` + +### AzDeploymentExistence [Test] `Boolean` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDeploymentOperation [Get] `IDeploymentOperation` + - DeploymentName `String` + - SubscriptionId `String[]` + - ResourceGroupName `String` + - OperationId `String` + - DeploymentObject `IDeploymentExtended` + - InputObject `IResourcesIdentity` + - Top `Int32` + +### AzDeploymentTemplate [Export] `IDeploymentExportResultTemplate` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDomain [Get] `IDomain` + - TenantId `String` + - Name `String` + - InputObject `IResourcesIdentity` + - Filter `String` + +### AzElevateGlobalAdministratorAccess [Invoke] `Boolean` + +### AzEntity [Get] `IEntityInfo` + - Filter `String` + - GroupName `String` + - Search `String` + - Select `String` + - Skip `Int32` + - Skiptoken `String` + - Top `Int32` + - View `String` + - CacheControl `String` + +### AzManagedApplication [Get, New, Remove, Set, Update] `IApplication, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplication` + - ApplicationDefinitionId `String` + - IdentityType `ResourceIdentityType` + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagedApplicationDefinition [Get, New, Remove, Set] `IApplicationDefinition, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplicationDefinition` + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - PackageFileUri `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagementGroup [Get, New, Remove, Set, Update] `IManagementGroup, IManagementGroupInfo, Boolean` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Expand `String` + - Filter `String` + - Recurse `SwitchParameter` + - CacheControl `String` + - DisplayName `String` + - Name `String` + - ParentId `String` + - CreateManagementGroupRequest `ICreateManagementGroupRequest` + - PatchGroupRequest `IPatchManagementGroupRequest` + +### AzManagementGroupDescendant [Get] `IDescendantInfo` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Top `Int32` + +### AzManagementGroupSubscription [New, Remove] `Boolean` + - GroupId `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - CacheControl `String` + +### AzManagementLock [Get, New, Remove, Set] `IManagementLockObject, Boolean` + - SubscriptionId `String[]` + - LockName `String` + - ResourceGroupName `String` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Level `LockLevel` + - Note `String` + - Owner `IManagementLockOwner[]` + - Parameter `IManagementLockObject` + +### AzNameAvailability [Test] `ICheckNameAvailabilityResult` + - Name `String` + - Type `Type` + - CheckNameAvailabilityRequest `ICheckNameAvailabilityRequest` + +### AzOAuth2PermissionGrant [Get, New, Remove] `IOAuth2PermissionGrant, Boolean` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ClientId `String` + - ConsentType `ConsentType` + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + - Body `IOAuth2PermissionGrant` + +### AzPermission [Get] `IPermission` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + +### AzPolicyAssignment [Get, New, Remove] `IPolicyAssignment` + - Id `String` + - Name `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - PolicyDefinitionId `String` + - IncludeDescendent `SwitchParameter` + - Filter `String` + - Parameter `IPolicyAssignment` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - SkuName `String` + - SkuTier `String` + - PropertiesScope `String` + +### AzPolicyDefinition [Get, New, Remove, Set] `IPolicyDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicyDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzPolicySetDefinition [Get, New, Remove, Set] `IPolicySetDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicySetDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzProviderFeature [Get, Register] `IFeatureResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + +### AzProviderOperationsMetadata [Get] `IProviderOperationsMetadata` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + +### AzResource [Get, Move, New, Remove, Set, Test, Update] `IGenericResource, Boolean` + - ResourceId `String` + - Name `String` + - ParentResourcePath `String` + - ProviderNamespace `String` + - ResourceGroupName `String` + - ResourceType `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - SourceResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - Expand `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Filter `String` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + - IdentityType `ResourceIdentityType` + - IdentityUserAssignedIdentity `Hashtable` + - Kind `String` + - Location `String` + - ManagedBy `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + +### AzResourceGroup [Export, Get, New, Remove, Set, Test, Update] `IResourceGroupExportResult, IResourceGroup, Boolean` + - ResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Id `String` + - Filter `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Option `String` + - Resource `String[]` + - Parameter `IExportTemplateRequest` + - Location `String` + - ManagedBy `String` + +### AzResourceLink [Get, New, Remove, Set] `IResourceLink, Boolean` + - ResourceId `String` + - InputObject `IResourcesIdentity` + - SubscriptionId `String[]` + - Scope `String` + - FilterById `String` + - FilterByScope `Filter` + - Note `String` + - TargetId `String` + - Parameter `IResourceLink` + +### AzResourceMove [Test] `Boolean` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + +### AzResourceProvider [Get, Register, Unregister] `IProvider` + - SubscriptionId `String[]` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + - Top `Int32` + +### AzResourceProviderOperationDetail [Get] `IResourceProviderOperationDefinition` + - ResourceProviderNamespace `String` + +### AzRoleAssignment [Get, New, Remove] `IRoleAssignment` + - Id `String` + - Name `String` + - Scope `String` + - RoleId `String` + - InputObject `IResourcesIdentity` + - ParentResourceId `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - ExpandPrincipalGroups `String` + - ServicePrincipalName `String` + - SignInName `String` + - Filter `String` + - CanDelegate `SwitchParameter` + - PrincipalId `String` + - RoleDefinitionId `String` + - Parameter `IRoleAssignmentCreateParameters` + - PrincipalType `PrincipalType` + +### AzRoleDefinition [Get, New, Remove, Set] `IRoleDefinition` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Custom `SwitchParameter` + - Filter `String` + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - RoleDefinition `IRoleDefinition` + +### AzSubscriptionLocation [Get] `ILocation` + - SubscriptionId `String[]` + +### AzTag [Get, New, Remove] `ITagDetails, Boolean` + - SubscriptionId `String[]` + - Name `String` + - Value `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + +### AzTenantBackfill [Start] `ITenantBackfillStatusResult` + +### AzTenantBackfillStatus [Invoke] `ITenantBackfillStatusResult` + diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/ModelSurface.md @@ -0,0 +1,1645 @@ +### AddOwnerParameters \ [Api16] + - Url `String` + +### AdGroup \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - Mail `String` + - MailEnabled `Boolean?` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - SecurityEnabled `Boolean?` + +### AliasPathType [Api20180501] + - ApiVersion `String[]` + - Path `String` + +### AliasType [Api20180501] + - Name `String` + - Path `IAliasPathType[]` + +### Appliance [Api20160901Preview] + - DefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceArtifact [Api20160901Preview] + - Name `String` + - Type `ApplianceArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplianceDefinition [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplianceDefinitionListResult [Api20160901Preview] + - NextLink `String` + - Value `IApplianceDefinition[]` + +### ApplianceDefinitionProperties [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - PackageFileUri `String` + +### ApplianceListResult [Api20160901Preview] + - NextLink `String` + - Value `IAppliance[]` + +### AppliancePatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceProperties [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### AppliancePropertiesPatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplianceProviderAuthorization [Api20160901Preview] + - PrincipalId `String` + - RoleDefinitionId `String` + +### Application \ [Api16, Api20170901, Api20180601] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppId `String` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DefinitionId `String` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - Id `String` + - IdentifierUri `String[]` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - Kind `String` + - KnownClientApplication `String[]` + - Location `String` + - LogoutUrl `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - ObjectId `String` + - ObjectType `String` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - PasswordCredentials `IPasswordCredential[]` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - ProvisioningState `String` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + - WwwHomepage `String` + +### ApplicationArtifact [Api20170901] + - Name `String` + - Type `ApplicationArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplicationBase [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationCreateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationDefinition [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplicationDefinitionListResult [Api20180601] + - NextLink `String` + - Value `IApplicationDefinition[]` + +### ApplicationDefinitionProperties [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IsEnabled `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - PackageFileUri `String` + +### ApplicationListResult [Api16, Api20180601] + - NextLink `String` + - OdataNextLink `String` + - Value `IApplication[]` + +### ApplicationPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplicationProperties [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationPropertiesPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationProviderAuthorization [Api20170901] + - PrincipalId `String` + - RoleDefinitionId `String` + +### ApplicationUpdateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### AppRole [Api16] + - AllowedMemberType `String[]` + - Description `String` + - DisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Value `String` + +### BasicDependency [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### CheckGroupMembershipParameters \ [Api16] + - GroupId `String` + - MemberId `String` + +### CheckGroupMembershipResult \ [Api16] + - Value `Boolean?` + +### CheckNameAvailabilityRequest [Api20180301Preview] + - Name `String` + - Type `Type?` **{ProvidersMicrosoftManagementGroups}** + +### CheckNameAvailabilityResult [Api20180301Preview] + - Message `String` + - NameAvailable `Boolean?` + - Reason `Reason?` **{AlreadyExists, Invalid}** + +### ClassicAdministrator [Api20150701] + - EmailAddress `String` + - Id `String` + - Name `String` + - Role `String` + - Type `String` + +### ClassicAdministratorListResult [Api20150701] + - NextLink `String` + - Value `IClassicAdministrator[]` + +### ClassicAdministratorProperties [Api20150701] + - EmailAddress `String` + - Role `String` + +### ComponentsSchemasIdentityPropertiesUserassignedidentitiesAdditionalproperties [Api20180501] + - ClientId `String` + - PrincipalId `String` + +### CreateManagementGroupChildInfo [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### CreateManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### CreateManagementGroupProperties [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### CreateManagementGroupRequest [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### CreateParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### DebugSetting [Api20180501] + - DetailLevel `String` + +### DenyAssignment [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - Id `String` + - IsSystemProtected `Boolean?` + - Name `String` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + - Type `String` + +### DenyAssignmentListResult [Api20180701Preview] + - NextLink `String` + - Value `IDenyAssignment[]` + +### DenyAssignmentPermission [Api20180701Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### DenyAssignmentProperties [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - IsSystemProtected `Boolean?` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + +### Dependency [Api20180501] + - DependsOn `IBasicDependency[]` + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### Deployment [Api20180501] + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentExportResult [Api20180501] + - Template `IDeploymentExportResultTemplate` + +### DeploymentExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Id `String` + - Location `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - Name `String` + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + - Type `String` + +### DeploymentListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentExtended[]` + +### DeploymentOperation [Api20180501] + - Id `String` + - OperationId `String` + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationProperties [Api20180501] + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationsListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentOperation[]` + +### DeploymentProperties [Api20180501] + - DebugSettingDetailLevel `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentPropertiesExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentValidateResult [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DescendantInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - ParentId `String` + - Type `String` + +### DescendantInfoProperties [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### DescendantListResult [Api20180301Preview] + - NextLink `String` + - Value `IDescendantInfo[]` + +### DescendantParentGroupInfo [Api20180301Preview] + - Id `String` + +### DirectoryObject \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - ObjectId `String` + - ObjectType `String` + +### DirectoryObjectListResult [Api16] + - OdataNextLink `String` + - Value `IDirectoryObject[]` + +### Domain \ [Api16] + - AuthenticationType `String` + - IsDefault `Boolean?` + - IsVerified `Boolean?` + - Name `String` + +### DomainListResult [Api16] + - Value `IDomain[]` + +### EntityInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - InheritedPermission `String` + - Name `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + - Type `String` + +### EntityInfoProperties [Api20180301Preview] + - DisplayName `String` + - InheritedPermission `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + +### EntityListResult [Api20180301Preview] + - Count `Int32?` + - NextLink `String` + - Value `IEntityInfo[]` + +### EntityParentGroupInfo [Api20180301Preview] + - Id `String` + +### ErrorDetails [Api20180301Preview] + - Code `String` + - Detail `String` + - Message `String` + +### ErrorMessage [Api16] + - Message `String` + +### ErrorResponse [Api20160901Preview, Api20180301Preview] + - ErrorCode `String` + - ErrorDetail `String` + - ErrorMessage `String` + - HttpStatus `String` + +### ExportTemplateRequest [Api20180501] + - Option `String` + - Resource `String[]` + +### FeatureOperationsListResult [Api20151201] + - NextLink `String` + - Value `IFeatureResult[]` + +### FeatureProperties [Api20151201] + - State `String` + +### FeatureResult [Api20151201] + - Id `String` + - Name `String` + - State `String` + - Type `String` + +### GenericResource [Api20160901Preview, Api20180501] + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IdentityUserAssignedIdentity `IIdentityUserAssignedIdentities ` + - Kind `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### GetObjectsParameters \ [Api16] + - IncludeDirectoryObjectReference `Boolean?` + - ObjectId `String[]` + - Type `String[]` + +### GraphError [Api16] + - ErrorMessageValueMessage `String` + - OdataErrorCode `String` + +### GroupAddMemberParameters \ [Api16] + - Url `String` + +### GroupCreateParameters \ [Api16] + - DisplayName `String` + - MailEnabled `Boolean` + - MailNickname `String` + - SecurityEnabled `Boolean` + +### GroupGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### GroupGetMemberGroupsResult [Api16] + - Value `String[]` + +### GroupListResult [Api16] + - OdataNextLink `String` + - Value `IAdGroup[]` + +### HttpMessage [Api20180501] + - Content `IHttpMessageContent` + +### Identity [Api20160901Preview, Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - UserAssignedIdentity `IIdentityUserAssignedIdentities ` + +### Identity1 [Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + +### InformationalUrl [Api16] + - Marketing `String` + - Privacy `String` + - Support `String` + - TermsOfService `String` + +### KeyCredential \ [Api16] + - CustomKeyIdentifier `String` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Type `String` + - Usage `String` + - Value `String` + +### KeyCredentialListResult [Api16] + - Value `IKeyCredential[]` + +### KeyCredentialsUpdateParameters [Api16] + - Value `IKeyCredential[]` + +### Location [Api20160601] + - DisplayName `String` + - Id `String` + - Latitude `String` + - Longitude `String` + - Name `String` + - SubscriptionId `String` + +### LocationListResult [Api20160601] + - Value `ILocation[]` + +### ManagementGroup [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### ManagementGroupChildInfo [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### ManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### ManagementGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - TenantId `String` + - Type `String` + +### ManagementGroupInfoProperties [Api20180301Preview] + - DisplayName `String` + - TenantId `String` + +### ManagementGroupListResult [Api20180301Preview] + - NextLink `String` + - Value `IManagementGroupInfo[]` + +### ManagementGroupProperties [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### ManagementLockListResult [Api20160901] + - NextLink `String` + - Value `IManagementLockObject[]` + +### ManagementLockObject [Api20160901] + - Id `String` + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Name `String` + - Note `String` + - Owner `IManagementLockOwner[]` + - Type `String` + +### ManagementLockOwner [Api20160901] + - ApplicationId `String` + +### ManagementLockProperties [Api20160901] + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Note `String` + - Owner `IManagementLockOwner[]` + +### OAuth2Permission [Api16] + - AdminConsentDescription `String` + - AdminConsentDisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Type `String` + - UserConsentDescription `String` + - UserConsentDisplayName `String` + - Value `String` + +### OAuth2PermissionGrant [Api16] + - ClientId `String` + - ConsentType `ConsentType?` **{AllPrincipals, Principal}** + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + +### OAuth2PermissionGrantListResult [Api16] + - OdataNextLink `String` + - Value `IOAuth2PermissionGrant[]` + +### OdataError [Api16] + - Code `String` + - ErrorMessageValueMessage `String` + +### OnErrorDeployment [Api20180501] + - DeploymentName `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### OnErrorDeploymentExtended [Api20180501] + - DeploymentName `String` + - ProvisioningState `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### Operation [Api20151201, Api20180301Preview] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayResource `String` + - Name `String` + +### OperationDisplay [Api20151201] + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationDisplayProperties [Api20180301Preview] + - Description `String` + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationListResult [Api20151201, Api20180301Preview] + - NextLink `String` + - Value `IOperation[]` + +### OperationResults [Api20180301Preview] + - Id `String` + - Name `String` + - ProvisioningState `String` + - Type `String` + +### OperationResultsProperties [Api20180301Preview] + - ProvisioningState `String` + +### OptionalClaim [Api16] + - AdditionalProperty `IOptionalClaimAdditionalProperties` + - Essential `Boolean?` + - Name `String` + - Source `String` + +### OptionalClaims [Api16] + - AccessToken `IOptionalClaim[]` + - IdToken `IOptionalClaim[]` + - SamlToken `IOptionalClaim[]` + +### ParametersLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### ParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### PasswordCredential \ [Api16] + - CustomKeyIdentifier `Byte[]` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Value `String` + +### PasswordCredentialListResult [Api16] + - Value `IPasswordCredential[]` + +### PasswordCredentialsUpdateParameters [Api16] + - Value `IPasswordCredential[]` + +### PasswordProfile \ [Api16] + - ForceChangePasswordNextLogin `Boolean?` + - Password `String` + +### PatchManagementGroupRequest [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### Permission [Api20150701, Api201801Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### PermissionGetResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IPermission[]` + +### Plan [Api20160901Preview, Api20180501] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PlanPatchable [Api20160901Preview] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PolicyAssignment [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - Name `String` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + - SkuName `String` + - SkuTier `String` + - Type `String` + +### PolicyAssignmentListResult [Api20151101, Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyAssignment[]` + +### PolicyAssignmentProperties [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + +### PolicyDefinition [Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Name `String` + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Property `IPolicyDefinitionProperties` + - Type `String` + +### PolicyDefinitionListResult [Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyDefinition[]` + +### PolicyDefinitionProperties [Api20161201] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicyDefinitionReference [Api20180501] + - Parameter `IPolicyDefinitionReferenceParameters` + - PolicyDefinitionId `String` + +### PolicySetDefinition [Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Name `String` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Type `String` + +### PolicySetDefinitionListResult [Api20180501] + - NextLink `String` + - Value `IPolicySetDefinition[]` + +### PolicySetDefinitionProperties [Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicySku [Api20180501] + - Name `String` + - Tier `String` + +### PreAuthorizedApplication [Api16] + - AppId `String` + - Extension `IPreAuthorizedApplicationExtension[]` + - Permission `IPreAuthorizedApplicationPermission[]` + +### PreAuthorizedApplicationExtension [Api16] + - Condition `String[]` + +### PreAuthorizedApplicationPermission [Api16] + - AccessGrant `String[]` + - DirectAccessGrant `Boolean?` + +### Principal [Api20180701Preview] + - Id `String` + - Type `String` + +### Provider [Api20180501] + - Id `String` + - Namespace `String` + - RegistrationState `String` + - ResourceType `IProviderResourceType[]` + +### ProviderListResult [Api20180501] + - NextLink `String` + - Value `IProvider[]` + +### ProviderOperation [Api20150701, Api201801Preview] + - Description `String` + - DisplayName `String` + - IsDataAction `Boolean?` + - Name `String` + - Origin `String` + - Property `IProviderOperationProperties` + +### ProviderOperationsMetadata [Api20150701, Api201801Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - Operation `IProviderOperation[]` + - ResourceType `IResourceType[]` + - Type `String` + +### ProviderOperationsMetadataListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IProviderOperationsMetadata[]` + +### ProviderResourceType [Api20180501] + - Alias `IAliasType[]` + - ApiVersion `String[]` + - Location `String[]` + - Property `IProviderResourceTypeProperties ` + - ResourceType `String` + +### RequiredResourceAccess \ [Api16] + - ResourceAccess `IResourceAccess[]` + - ResourceAppId `String` + +### Resource [Api20160901Preview] + - Id `String` + - Location `String` + - Name `String` + - Tag `IResourceTags ` + - Type `String` + +### ResourceAccess \ [Api16] + - Id `String` + - Type `String` + +### ResourceGroup [Api20180501] + - Id `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupTags ` + - Type `String` + +### ResourceGroupExportResult [Api20180501] + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Template `IResourceGroupExportResultTemplate` + +### ResourceGroupListResult [Api20180501] + - NextLink `String` + - Value `IResourceGroup[]` + +### ResourceGroupPatchable [Api20180501] + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupPatchableTags ` + +### ResourceGroupProperties [Api20180501] + - ProvisioningState `String` + +### ResourceLink [Api20160901] + - Id `String` + - Name `String` + - Note `String` + - SourceId `String` + - TargetId `String` + - Type `IResourceLinkType` + +### ResourceLinkProperties [Api20160901] + - Note `String` + - SourceId `String` + - TargetId `String` + +### ResourceLinkResult [Api20160901] + - NextLink `String` + - Value `IResourceLink[]` + +### ResourceListResult [Api20180501] + - NextLink `String` + - Value `IGenericResource[]` + +### ResourceManagementErrorWithDetails [Api20180501] + - Code `String` + - Detail `IResourceManagementErrorWithDetails[]` + - Message `String` + - Target `String` + +### ResourceProviderOperationDefinition [Api20151101] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayPublisher `String` + - DisplayResource `String` + - Name `String` + +### ResourceProviderOperationDetailListResult [Api20151101] + - NextLink `String` + - Value `IResourceProviderOperationDefinition[]` + +### ResourceProviderOperationDisplayProperties [Api20151101] + - Description `String` + - Operation `String` + - Provider `String` + - Publisher `String` + - Resource `String` + +### ResourcesIdentity [Models] + - ApplianceDefinitionId `String` + - ApplianceDefinitionName `String` + - ApplianceId `String` + - ApplianceName `String` + - ApplicationDefinitionId `String` + - ApplicationDefinitionName `String` + - ApplicationId `String` + - ApplicationId1 `String` + - ApplicationName `String` + - ApplicationObjectId `String` + - DenyAssignmentId `String` + - DeploymentName `String` + - DomainName `String` + - FeatureName `String` + - GroupId `String` + - GroupObjectId `String` + - Id `String` + - LinkId `String` + - LockName `String` + - ManagementGroupId `String` + - MemberObjectId `String` + - ObjectId `String` + - OperationId `String` + - OwnerObjectId `String` + - ParentResourcePath `String` + - PolicyAssignmentId `String` + - PolicyAssignmentName `String` + - PolicyDefinitionName `String` + - PolicySetDefinitionName `String` + - ResourceGroupName `String` + - ResourceId `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - RoleAssignmentId `String` + - RoleAssignmentName `String` + - RoleDefinitionId `String` + - RoleId `String` + - Scope `String` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - TagName `String` + - TagValue `String` + - TenantId `String` + - UpnOrObjectId `String` + +### ResourcesMoveInfo [Api20180501] + - Resource `String[]` + - TargetResourceGroup `String` + +### ResourceType [Api20150701, Api201801Preview] + - DisplayName `String` + - Name `String` + - Operation `IProviderOperation[]` + +### RoleAssignment [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - Id `String` + - Name `String` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + - Type `String` + +### RoleAssignmentCreateParameters [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentListResult [Api20150701, Api20180901Preview] + - NextLink `String` + - Value `IRoleAssignment[]` + +### RoleAssignmentProperties [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentPropertiesWithScope [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + +### RoleDefinition [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Id `String` + - Name `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - Type `String` + +### RoleDefinitionListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IRoleDefinition[]` + +### RoleDefinitionProperties [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + +### ServicePrincipal \ [Api16] + - AccountEnabled `Boolean?` + - AlternativeName `String[]` + - AppDisplayName `String` + - AppId `String` + - AppOwnerTenantId `String` + - AppRole `IAppRole[]` + - AppRoleAssignmentRequired `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - Homepage `String` + - KeyCredentials `IKeyCredential[]` + - LogoutUrl `String` + - Name `String[]` + - Oauth2Permission `IOAuth2Permission[]` + - ObjectId `String` + - ObjectType `String` + - PasswordCredentials `IPasswordCredential[]` + - PreferredTokenSigningKeyThumbprint `String` + - PublisherName `String` + - ReplyUrl `String[]` + - SamlMetadataUrl `String` + - Tag `String[]` + - Type `String` + +### ServicePrincipalBase [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalCreateParameters [Api16] + - AccountEnabled `Boolean?` + - AppId `String` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalListResult [Api16] + - OdataNextLink `String` + - Value `IServicePrincipal[]` + +### ServicePrincipalObjectResult [Api16] + - OdataMetadata `String` + - Value `String` + +### ServicePrincipalUpdateParameters [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### SignInName \ [Api16] + - Type `String` + - Value `String` + +### Sku [Api20160901Preview, Api20180501] + - Capacity `Int32?` + - Family `String` + - Model `String` + - Name `String` + - Size `String` + - Tier `String` + +### Subscription [Api20160601] + - AuthorizationSource `String` + - DisplayName `String` + - Id `String` + - PolicyLocationPlacementId `String` + - PolicyQuotaId `String` + - PolicySpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + - State `SubscriptionState?` **{Deleted, Disabled, Enabled, PastDue, Warned}** + - SubscriptionId `String` + +### SubscriptionPolicies [Api20160601] + - LocationPlacementId `String` + - QuotaId `String` + - SpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + +### TagCount [Api20180501] + - Type `String` + - Value `Int32?` + +### TagDetails [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagName `String` + - Value `ITagValue[]` + +### TagsListResult [Api20180501] + - NextLink `String` + - Value `ITagDetails[]` + +### TagValue [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagValue1 `String` + +### TargetResource [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### TemplateLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### TenantBackfillStatusResult [Api20180301Preview] + - Status `Status?` **{Cancelled, Completed, Failed, NotStarted, NotStartedButGroupsExist, Started}** + - TenantId `String` + +### TenantIdDescription [Api20160601] + - Id `String` + - TenantId `String` + +### TenantListResult [Api20160601] + - NextLink `String` + - Value `ITenantIdDescription[]` + +### User \ [Api16] + - AccountEnabled `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - PrincipalName `String` + - SignInName `ISignInName[]` + - Surname `String` + - Type `UserType?` **{Guest, Member}** + - UsageLocation `String` + +### UserBase \ [Api16] + - GivenName `String` + - ImmutableId `String` + - Surname `String` + - UsageLocation `String` + - UserType `UserType?` **{Guest, Member}** + +### UserCreateParameters \ [Api16] + - AccountEnabled `Boolean` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + +### UserGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### UserGetMemberGroupsResult [Api16] + - Value `String[]` + +### UserListResult [Api16] + - OdataNextLink `String` + - Value `IUser[]` + +### UserUpdateParameters \ [Api16] + - AccountEnabled `Boolean?` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/tools/Resources/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/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/target/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Neon.Postgres.Management/tspconfig.yaml b/tests-upgrade/tests-emitter/Neon.Postgres.Management/tspconfig.yaml new file mode 100644 index 00000000000..9b021c47c5b --- /dev/null +++ b/tests-upgrade/tests-emitter/Neon.Postgres.Management/tspconfig.yaml @@ -0,0 +1,88 @@ +output-dir: "{project-root}/" +parameters: + "service-dir": + default: "sdk/neonpostgres" +emit: + - "@azure-tools/typespec-autorest" +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" +options: + "@azure-tools/typespec-autorest": + use-read-only-status-schema: true + emitter-output-dir: "{project-root}/.." + azure-resource-provider-folder: "resource-manager" + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/neon.json" + examples-dir: "{project-root}/examples" + "@azure-tools/typespec-csharp": + flavor: azure + clear-output-folder: true + package-dir: "Azure.ResourceManager.NeonPostgres" + namespace: "Azure.ResourceManager.NeonPostgres" + model-namespace: false + generate-sample-project: false + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-neonpostgres" + package-name: "{package-dir}" + flavor: "azure" + generate-test: true + generate-sample: true + "@azure-tools/typespec-java": + package-dir: "azure-resourcemanager-neonpostgres" + namespace: "com.azure.resourcemanager.neonpostgres" + service-name: "Neon Postgres" + flavor: "azure" + "@azure-tools/typespec-go": + service-dir: "sdk/resourcemanager/neonpostgres" + package-dir: "armneonpostgres" + module: "github.com/Azure/azure-sdk-for-go/{service-dir}/{package-dir}" + fix-const-stuttering: true + flavor: "azure" + generate-examples: true + generate-fakes: true + head-as-boolean: true + inject-spans: true + remove-unreferenced-types: true + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "NeonPostgres/NeonPostgres.Autorest" + clear-output-folder: true + azure: true + module-version: 0.1.0 + skip-model-cmdlets: false + help-link-prefix: https://learn.microsoft.com/powershell/module/ + metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + description: 'Microsoft Azure PowerShell: NeonPostgres cmdlets' + copyright: Microsoft Corporation. All rights reserved. + tags: Azure ResourceManager ARM PSModule Sphere + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell + prefix: 'Az' + subject-prefix: 'NeonPostgres' + service-name: NeonPostgres + module-name: "{prefix}.{service-name}" + namespace: "Microsoft.Azure.PowerShell.Cmdlets.{service-name}" + use-namespace-folders: false + # output-folder: "{output-dir}" + exclude-tableview-properties: + - Id + - Type + directive: + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - where: + variant: ^(Create|Update)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + verb: Set + hide: true diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase.Storage/main.tsp b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase.Storage/main.tsp new file mode 100644 index 00000000000..f693c72d920 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase.Storage/main.tsp @@ -0,0 +1,138 @@ +import "./../LiftrBase/main.tsp"; + +import "@typespec/openapi"; +import "@typespec/http"; +import "@typespec/rest"; +import "@typespec/versioning"; + +using Azure.ResourceManager; +using LiftrBase; +using TypeSpec.Http; +using TypeSpec.OpenAPI; +using TypeSpec.Rest; +using TypeSpec.Versioning; +using TypeSpec.Reflection; +using Azure.ResourceManager.Foundations; + +@versioned(LiftrBase.Storage.Versions) +@armLibraryNamespace +namespace LiftrBase.Storage; + +@doc("Supported versions for LiftrBase.Storage resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1 and LiftrBase.Versions.v1_preview") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2_preview) + @armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v3) + v2_preview: "2024-02-01-preview", +} + +/** + * Properties specific to the Qumulo File System resource + */ +model FileSystemResourceProperties { + /** + * Marketplace details + */ + marketplaceDetails: MarketplaceDetails; + + /** + * Provisioning State of the resource + */ + @visibility("read") + provisioningState?: ProvisioningState; + + /** + * Storage Sku + */ + storageSku: string; + + /** + * User Details + */ + userDetails: UserDetails; + + /** + * Delegated subnet id for Vnet injection + */ + delegatedSubnetId: string; + + /** + * File system Id of the resource + */ + clusterLoginUrl?: string; + + /** + * Private IPs of the resource + */ + #suppress "@azure-tools/typespec-azure-core/casing-style" "This is the correct name" + privateIPs?: string[]; + + /** + * Initial administrator password of the resource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Legacy" + @extension("x-ms-secret", true) + adminPassword: string; + + /** + * Availability zone + */ + availabilityZone?: string; +} + +/** + * The type used for update operations of the FileSystemResource. + */ +model FileSystemResourceUpdate { + /** + * The managed service identities assigned to this resource. + */ + identity?: Azure.ResourceManager.CommonTypes.ManagedServiceIdentity; + + /** + * Resource tags. + */ + #suppress "@azure-tools/typespec-azure-resource-manager/arm-no-record" "existing API" + tags?: Record; + + /** + * The updatable properties of the FileSystemResource. + */ + properties?: FileSystemResourceUpdateProperties; +} + +/** + * The updatable properties of the FileSystemResource. + */ +model FileSystemResourceUpdateProperties { + /** + * Marketplace details + */ + marketplaceDetails?: MarketplaceDetails; + + /** + * User Details + */ + userDetails?: UserDetails; + + /** + * Delegated subnet id for Vnet injection + */ + delegatedSubnetId?: string; +} + +model FileSystemResource + is Azure.ResourceManager.TrackedResource { + /** + * Name of the File System resource + */ + @path + @key("fileSystemName") + @segment("fileSystems") + @visibility("read") + @pattern("^[a-zA-Z0-9_-]*$") + name: string; + + ...Azure.ResourceManager.ManagedServiceIdentityProperty; +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase/main.tsp b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase/main.tsp new file mode 100644 index 00000000000..066f7f1ef70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/LiftrBase/main.tsp @@ -0,0 +1,140 @@ +import "@azure-tools/typespec-autorest"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; + +using Azure.ResourceManager; +using TypeSpec.Versioning; +using TypeSpec.Reflection; +using TypeSpec.OpenAPI; + +@versioned(LiftrBase.Versions) +namespace LiftrBase; + +@doc("Supported versions for LiftrBase resource model") +enum Versions { + @doc("Dependent on Azure.ResourceManager.Versions.v1_0_Preview_1") + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v3) + v2_preview: "2024-02-01-preview", +} + +/** + * Marketplace subscription status of the file system resource + */ +union MarketplaceSubscriptionStatus { + /** + * Fulfillment has not started + */ + PendingFulfillmentStart: "PendingFulfillmentStart", + + /** + * Marketplace offer is subscribed + */ + Subscribed: "Subscribed", + + /** + * Marketplace offer is suspended because of non payment + */ + Suspended: "Suspended", + + /** + * Marketplace offer is unsubscribed + */ + Unsubscribed: "Unsubscribed", + + string, +} + +@doc("MarketplaceDetails of Qumulo FileSystem resource") +model MarketplaceDetails { + /** + * Marketplace Subscription Id + */ + marketplaceSubscriptionId?: string; + + /** + * Plan Id + */ + planId: string; + + /** + * Offer Id + */ + offerId: string; + + /** + * Publisher Id + */ + publisherId?: string; + + /** + * Term Unit + */ + termUnit?: string; + + /** + * Marketplace subscription status + */ + @visibility("read") + marketplaceSubscriptionStatus?: MarketplaceSubscriptionStatus; +} + +@doc("User Details of Qumulo FileSystem resource") +model UserDetails { + /** + * User Email + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "Legacy" + @extension("x-ms-secret", true) + email: string; +} + +/** + * Provisioning State of the File system resource + */ +union ProvisioningState { + /** + * File system resource creation request accepted + */ + Accepted: "Accepted", + + /** + * File system resource creation started + */ + Creating: "Creating", + + /** + * File system resource is being updated + */ + Updating: "Updating", + + /** + * File system resource deletion started + */ + Deleting: "Deleting", + + /** + * File system resource creation successful + */ + Succeeded: "Succeeded", + + /** + * File system resource creation failed + */ + Failed: "Failed", + + /** + * File system resource creation canceled + */ + Canceled: "Canceled", + + /** + * File system resource is deleted + */ + Deleted: "Deleted", + + string, +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/client.tsp b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/client.tsp new file mode 100644 index 00000000000..2c4639cf19c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/client.tsp @@ -0,0 +1,6 @@ +import "./main.tsp"; +import "@azure-tools/typespec-client-generator-core"; + +using Azure.ClientGenerator.Core; + +@@clientName(Qumulo.Storage, "QumuloMgmt", "python"); diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MaximumSet_Gen.json new file mode 100644 index 00000000000..0a5033a3a8a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MaximumSet_Gen.json @@ -0,0 +1,147 @@ +{ + "title": "FileSystems_CreateOrUpdate", + "operationId": "FileSystems_CreateOrUpdate", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo", + "fileSystemName": "hfcmtgaes", + "resource": { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "storageSku": "yhyzby", + "userDetails": { + "email": "aqsnzyroo" + }, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "adminPassword": "fakeTestSecretPlaceholder", + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "type": "None", + "userAssignedIdentities": { + "key7679": {} + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb" + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + }, + "201": { + "headers": { + "Retry-After": 10, + "Azure-AsyncOperation": "https://contoso.com/operationstatus" + }, + "body": { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MinimumSet_Gen.json new file mode 100644 index 00000000000..53811b13e3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_CreateOrUpdate_MinimumSet_Gen.json @@ -0,0 +1,71 @@ +{ + "parameters": { + "api-version": "2024-06-19", + "fileSystemName": "aaaaaaaa", + "resource": { + "location": "aaaaaaaaaaaaaaaaaaaaaaaaa", + "properties": { + "adminPassword": "fakeTestSecretPlaceholder", + "delegatedSubnetId": "aaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaaaaaaaaaaaaaaaaaa", + "planId": "aaaaaa" + }, + "storageSku": "Standard", + "userDetails": { + "email": "viptslwulnpaupfljvnjeq" + } + } + }, + "resourceGroupName": "rgopenapi", + "subscriptionId": "aaaaaaaaaaaaaaaaaaaaaaaa" + }, + "responses": { + "200": { + "body": { + "id": "aaaaaaaaaaaaaaaaa", + "location": "aaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaaaaaaaaaaaaaaaaaa", + "planId": "aaaaaa", + "publisherId": "aa" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + } + }, + "201": { + "body": { + "id": "aaaaaaaaaaaaaaaaa", + "location": "aaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaaaaaaaaaaaaaaaaaa", + "planId": "aaaaaa", + "publisherId": "aa" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + }, + "headers": { + "Retry-After": 10, + "Azure-AsyncOperation": "https://foo.com/operationstatus" + } + } + }, + "operationId": "FileSystems_CreateOrUpdate", + "title": "FileSystems_CreateOrUpdate_MinimumSet_Gen" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MaximumSet_Gen.json new file mode 100644 index 00000000000..ad172412489 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MaximumSet_Gen.json @@ -0,0 +1,19 @@ +{ + "title": "FileSystems_Delete", + "operationId": "FileSystems_Delete", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo", + "fileSystemName": "xoschzkccroahrykedlvbbnsddq" + }, + "responses": { + "202": { + "headers": { + "Retry-After": 10, + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MinimumSet_Gen.json new file mode 100644 index 00000000000..d28e0ae5ed9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Delete_MinimumSet_Gen.json @@ -0,0 +1,19 @@ +{ + "title": "FileSystems_Delete_MinimumSet_Gen", + "operationId": "FileSystems_Delete", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo", + "fileSystemName": "jgtskkiplquyrlkaxvhdg" + }, + "responses": { + "202": { + "headers": { + "Retry-After": 10, + "location": "https://contoso.com/operationstatus" + } + }, + "204": {} + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MaximumSet_Gen.json new file mode 100644 index 00000000000..5b60318e3d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MaximumSet_Gen.json @@ -0,0 +1,61 @@ +{ + "title": "FileSystems_Get", + "operationId": "FileSystems_Get", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo", + "fileSystemName": "sihbehcisdqtqqyfiewiiaphgh" + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MinimumSet_Gen.json new file mode 100644 index 00000000000..d24f92bc033 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Get_MinimumSet_Gen.json @@ -0,0 +1,32 @@ +{ + "parameters": { + "api-version": "2024-06-19", + "fileSystemName": "aaaaaaaaaaaaaaaaa", + "resourceGroupName": "rgQumulo", + "subscriptionId": "aaaaaaa" + }, + "responses": { + "200": { + "body": { + "name": "aaaaa", + "id": "aaaaaaaaaaaaaaaaa", + "location": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaa", + "planId": "aaaaaaa", + "termUnit": "zxv" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + } + } + }, + "operationId": "FileSystems_Get", + "title": "FileSystems_Get_MinimumSet_Gen" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MaximumSet_Gen.json new file mode 100644 index 00000000000..bbecaa117da --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MaximumSet_Gen.json @@ -0,0 +1,65 @@ +{ + "title": "FileSystems_ListByResourceGroup", + "operationId": "FileSystems_ListByResourceGroup", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MinimumSet_Gen.json new file mode 100644 index 00000000000..835ecfb7120 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListByResourceGroup_MinimumSet_Gen.json @@ -0,0 +1,34 @@ +{ + "parameters": { + "api-version": "2024-06-19", + "resourceGroupName": "rgQumulo", + "subscriptionId": "aaaaaaa" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "aaaaa", + "id": "aaaaaaaaaaaaaaaaa", + "location": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaa", + "planId": "aaaaaaa" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + } + ] + } + } + }, + "operationId": "FileSystems_ListByResourceGroup", + "title": "FileSystems_ListByResourceGroup_MinimumSet_Gen" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MaximumSet_Gen.json new file mode 100644 index 00000000000..2b22140e5c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MaximumSet_Gen.json @@ -0,0 +1,64 @@ +{ + "title": "FileSystems_ListBySubscription", + "operationId": "FileSystems_ListBySubscription", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + ], + "nextLink": "https://microsoft.com/a" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MinimumSet_Gen.json new file mode 100644 index 00000000000..4a9979aab1c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_ListBySubscription_MinimumSet_Gen.json @@ -0,0 +1,33 @@ +{ + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "aaaaaaa" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "aaaaa", + "id": "aaaaaaaaaaaaaaaaa", + "location": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaa", + "planId": "aaaaaaa" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + } + ] + } + } + }, + "operationId": "FileSystems_ListBySubscription", + "title": "FileSystems_ListBySubscription_MinimumSet_Gen" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MaximumSet_Gen.json new file mode 100644 index 00000000000..c14f0292301 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MaximumSet_Gen.json @@ -0,0 +1,86 @@ +{ + "title": "FileSystems_Update", + "operationId": "FileSystems_Update", + "parameters": { + "api-version": "2024-06-19", + "subscriptionId": "382E8C7A-AC80-4D70-8580-EFE99537B9B7", + "resourceGroupName": "rgQumulo", + "fileSystemName": "ahpixnvykleksjlr", + "properties": { + "identity": { + "type": "None", + "userAssignedIdentities": { + "key7679": {} + } + }, + "tags": { + "key357": "ztkkvhfia" + }, + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "userDetails": { + "email": "aqsnzyroo" + }, + "delegatedSubnetId": "bqaryqsjlackxphpmzffgoqsvm" + } + } + }, + "responses": { + "200": { + "body": { + "properties": { + "marketplaceDetails": { + "marketplaceSubscriptionId": "xaqtkloiyovmexqhn", + "planId": "fwtpz", + "offerId": "s", + "publisherId": "czxcfrwodazyaft", + "termUnit": "cfwwczmygsimcyvoclcw", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart" + }, + "provisioningState": "Accepted", + "storageSku": "yhyzby", + "userDetails": {}, + "delegatedSubnetId": "jykmxrf", + "clusterLoginUrl": "ykaynsjvhihdthkkvvodjrgc", + "privateIPs": [ + "gzken" + ], + "availabilityZone": "eqdvbdiuwmhhzqzmksmwllpddqquwt" + }, + "identity": { + "principalId": "11111111-1111-1111-1111-111111111111", + "tenantId": "11111111-1111-1111-1111-111111111111", + "type": "None", + "userAssignedIdentities": { + "key7679": { + "principalId": "11111111-1111-1111-1111-111111111111", + "clientId": "11111111-1111-1111-1111-111111111111" + } + } + }, + "tags": { + "key7090": "rurrdiaqp" + }, + "location": "pnb", + "id": "rfta", + "name": "stftolw", + "type": "wj", + "systemData": { + "createdBy": "usnkckwkizihezb", + "createdByType": "User", + "createdAt": "2024-03-21T08:11:54.895Z", + "lastModifiedBy": "yjsiqdgtsmycxlncjceemlucn", + "lastModifiedByType": "User", + "lastModifiedAt": "2024-03-21T08:11:54.895Z" + } + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MinimumSet_Gen.json new file mode 100644 index 00000000000..2199c9f27d4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/FileSystems_Update_MinimumSet_Gen.json @@ -0,0 +1,31 @@ +{ + "parameters": { + "api-version": "2024-06-19", + "fileSystemName": "aaaaaaaaaaaaaaaaa", + "properties": {}, + "resourceGroupName": "rgQumulo", + "subscriptionId": "aaaaaaa" + }, + "responses": { + "200": { + "body": { + "name": "aaaaa", + "location": "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "properties": { + "delegatedSubnetId": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "marketplaceDetails": { + "marketplaceSubscriptionId": "aaaaaaaaaaaaaaaaa", + "marketplaceSubscriptionStatus": "PendingFulfillmentStart", + "offerId": "aaaaaaaaa", + "planId": "aaaaaaa" + }, + "provisioningState": "Accepted", + "storageSku": "Standard", + "userDetails": {} + } + } + } + }, + "operationId": "FileSystems_Update", + "title": "FileSystems_Update_MinimumSet_Gen" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MaximumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MaximumSet_Gen.json new file mode 100644 index 00000000000..1eb2670e6c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MaximumSet_Gen.json @@ -0,0 +1,28 @@ +{ + "title": "Operations_List", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-06-19" + }, + "responses": { + "200": { + "body": { + "value": [ + { + "name": "melhpzamnyx", + "isDataAction": true, + "display": { + "provider": "ilyrhd", + "resource": "vjz", + "operation": "ayfoeuuyhtwjafroqzimyujr", + "description": "vodhl" + }, + "origin": "user", + "actionType": "Internal" + } + ], + "nextLink": "vxtunikmzmz" + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MinimumSet_Gen.json b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MinimumSet_Gen.json new file mode 100644 index 00000000000..4f4302e4807 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/examples/2024-06-19/Operations_List_MinimumSet_Gen.json @@ -0,0 +1,12 @@ +{ + "title": "Operations_List_MinimumSet_Gen", + "operationId": "Operations_List", + "parameters": { + "api-version": "2024-06-19" + }, + "responses": { + "200": { + "body": {} + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/main.tsp b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/main.tsp new file mode 100644 index 00000000000..e634bb7bc3d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/main.tsp @@ -0,0 +1,95 @@ +import "./LiftrBase.Storage/main.tsp"; + +import "@typespec/rest"; +import "@typespec/openapi"; +import "@typespec/versioning"; +import "@azure-tools/typespec-azure-core"; +import "@azure-tools/typespec-azure-resource-manager"; + +using TypeSpec.Rest; +using TypeSpec.OpenAPI; +using TypeSpec.Http; +using Azure.ResourceManager.Foundations; +using Azure.Core; +using Azure.ResourceManager; +using TypeSpec.Versioning; +using LiftrBase.Storage; +using LiftrBase; + +@armProviderNamespace +@useLibraryNamespace(LiftrBase.Storage) +@service({ + title: "Qumulo.Storage", +}) +@versioned(Versions) +namespace Qumulo.Storage; + +/** + * The available API versions. + */ +enum Versions { + /** + * The 2024-06-19 Stable API version. + */ + @useDependency(Azure.ResourceManager.Versions.v1_0_Preview_1) + @useDependency(LiftrBase.Versions.v2_preview) + @useDependency(LiftrBase.Storage.Versions.v2_preview) + @armCommonTypesVersion(Azure.ResourceManager.CommonTypes.Versions.v3) + v2_stable: "2024-06-19", +} + +interface Operations extends Azure.ResourceManager.Operations {} + +@armResourceOperations +interface FileSystems { + /** + * Get a FileSystemResource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @operationId("FileSystems_Get") + get is ArmResourceRead; + + /** + * Create a FileSystemResource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @operationId("FileSystems_CreateOrUpdate") + createOrUpdate is ArmResourceCreateOrReplaceAsync< + FileSystemResource, + BaseParameters, + ArmAsyncOperationHeader & Azure.Core.Foundations.RetryAfterHeader + >; + + /** + * Update a FileSystemResource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @parameterVisibility + @operationId("FileSystems_Update") + update is ArmCustomPatchSync; + + /** + * Delete a FileSystemResource + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @operationId("FileSystems_Delete") + delete is ArmResourceDeleteWithoutOkAsync< + FileSystemResource, + BaseParameters, + ArmCombinedLroHeaders & Azure.Core.Foundations.RetryAfterHeader + >; + + /** + * List FileSystemResource resources by resource group + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @operationId("FileSystems_ListByResourceGroup") + listByResourceGroup is ArmResourceListByParent; + + /** + * List FileSystemResource resources by subscription ID + */ + #suppress "@azure-tools/typespec-azure-core/no-openapi" "For backward compatibility" + @operationId("FileSystems_ListBySubscription") + listBySubscription is ArmListBySubscription; +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/.gitattributes b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.csproj b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.csproj new file mode 100644 index 00000000000..591ca173af0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.csproj @@ -0,0 +1,44 @@ + + + + 0.1.0 + 7.1 + netstandard2.0 + Library + Az.Qumulo.private + false + Microsoft.Azure.PowerShell.Cmdlets.Qumulo + true + false + ./bin + $(OutputPath) + Az.Qumulo.nuspec + true + + + 1998, 1591 + true + + + + false + TRACE;DEBUG;NETSTANDARD + + + + true + true + MSSharedLibKey.snk + TRACE;RELEASE;NETSTANDARD;SIGN + + + + + + + + + $(DefaultItemExcludes);resources/** + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.nuspec b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.nuspec new file mode 100644 index 00000000000..658fdaf7671 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.nuspec @@ -0,0 +1,32 @@ + + + + Az.Qumulo + 0.1.0 + Microsoft Corporation + Microsoft Corporation + true + https://aka.ms/azps-license + https://github.com/Azure/azure-powershell + Microsoft Azure PowerShell: Qumulo cmdlets + + Microsoft Corporation. All rights reserved. + Azure ResourceManager ARM PSModule Sphere + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.psm1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.psm1 new file mode 100644 index 00000000000..445a83543a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/Az.Qumulo.psm1 @@ -0,0 +1,119 @@ +# region Generated + # ---------------------------------------------------------------------------------- + # Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. + # ---------------------------------------------------------------------------------- + # Load required Az.Accounts module + $accountsName = 'Az.Accounts' + $accountsModule = Get-Module -Name $accountsName + if(-not $accountsModule) { + $localAccountsPath = Join-Path $PSScriptRoot 'generated\modules' + if(Test-Path -Path $localAccountsPath) { + $localAccounts = Get-ChildItem -Path $localAccountsPath -Recurse -Include 'Az.Accounts.psd1' | Select-Object -Last 1 + if($localAccounts) { + $accountsModule = Import-Module -Name ($localAccounts.FullName) -Scope Global -PassThru + } + } + if(-not $accountsModule) { + $hasAdequateVersion = (Get-Module -Name $accountsName -ListAvailable | Where-Object { $_.Version -ge [System.Version]'2.7.5' } | Measure-Object).Count -gt 0 + if($hasAdequateVersion) { + $accountsModule = Import-Module -Name $accountsName -MinimumVersion 2.7.5 -Scope Global -PassThru + } + } + } + + if(-not $accountsModule) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. For installation instructions, please see: https://learn.microsoft.com/powershell/azure/install-az-ps" -ErrorAction Stop + } elseif (($accountsModule.Version -lt [System.Version]'2.7.5') -and (-not $localAccounts)) { + Write-Error "`nThis module requires $accountsName version 2.7.5 or greater. An earlier version of Az.Accounts is imported in the current PowerShell session. If you are running test, please try to add the switch '-RegenerateSupportModule' when executing 'test-module.ps1'. Otherwise please open a new PowerShell session and import this module again.`nAdditionally, this error could indicate that multiple incompatible versions of Azure PowerShell modules are installed on your system. For troubleshooting information, please see: https://aka.ms/azps-version-error" -ErrorAction Stop + } + Write-Information "Loaded Module '$($accountsModule.Name)'" + + # Load the private module dll + $null = Import-Module -Name (Join-Path $PSScriptRoot './bin/Az.Qumulo.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module]::Instance + + # Ask for the shared functionality table + $VTable = Register-AzModule + + # Tweaks the pipeline on module load + $instance.OnModuleLoad = $VTable.OnModuleLoad + + # Following two delegates are added for telemetry + $instance.GetTelemetryId = $VTable.GetTelemetryId + $instance.Telemetry = $VTable.Telemetry + + # Delegate to sanitize the output object + $instance.SanitizeOutput = $VTable.SanitizerHandler + + # Delegate to get the telemetry info + $instance.GetTelemetryInfo = $VTable.GetTelemetryInfo + + # Tweaks the pipeline per call + $instance.OnNewRequest = $VTable.OnNewRequest + + # Gets shared parameter values + $instance.GetParameterValue = $VTable.GetParameterValue + + # Allows shared module to listen to events from this module + $instance.EventListener = $VTable.EventListener + + # Gets shared argument completers + $instance.ArgumentCompleter = $VTable.ArgumentCompleter + + # The name of the currently selected Azure profile + $instance.ProfileName = $VTable.ProfileName + + # Load the custom module + $customModulePath = Join-Path $PSScriptRoot './custom/Az.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/MSSharedLibKey.snk b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/MSSharedLibKey.snk new file mode 100644 index 00000000000..695f1b38774 Binary files /dev/null and b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/MSSharedLibKey.snk differ diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/README.md new file mode 100644 index 00000000000..d41dd214082 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/README.md @@ -0,0 +1,24 @@ + +# Az.Qumulo +This directory contains the PowerShell module for the Qumulo service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Qumulo`, see [how-to.md](how-to.md). + diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/build-module.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/build-module.ps1 new file mode 100644 index 00000000000..5026d3ed8bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/build-module.ps1 @@ -0,0 +1,191 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Run, [switch]$Test, [switch]$Docs, [switch]$Pack, [switch]$Code, [switch]$Release, [switch]$Debugger, [switch]$NoDocs, [switch]$UX, [Switch]$DisableAfterBuildTasks) +$ErrorActionPreference = 'Stop' + +if($PSEdition -ne 'Core') { + Write-Error 'This script requires PowerShell Core to execute. [Note] Generated cmdlets will work in both PowerShell Core or Windows PowerShell.' +} + +if(-not $NotIsolated -and -not $Debugger) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + + if($LastExitCode -ne 0) { + # Build failed. Don't attempt to run the module. + return + } + + if($Test) { + . (Join-Path $PSScriptRoot 'test-module.ps1') + if($LastExitCode -ne 0) { + # Tests failed. Don't attempt to run the module. + return + } + } + + if($Docs) { + . (Join-Path $PSScriptRoot 'generate-help.ps1') + if($LastExitCode -ne 0) { + # Docs generation failed. Don't attempt to run the module. + return + } + } + + if($UX) { + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') + if($LastExitCode -ne 0) { + # UX generation failed. Don't attempt to run the module. + return + } + } + + if($Pack) { + . (Join-Path $PSScriptRoot 'pack-module.ps1') + if($LastExitCode -ne 0) { + # Packing failed. Don't attempt to run the module. + return + } + } + + $runModulePath = Join-Path $PSScriptRoot 'run-module.ps1' + if($Code) { + . $runModulePath -Code + } elseif($Run) { + . $runModulePath + } else { + Write-Host -ForegroundColor Cyan "To run this module in an isolated PowerShell session, run the 'run-module.ps1' script or provide the '-Run' parameter to this script." + } + return +} + +$binFolder = Join-Path $PSScriptRoot 'bin' +$objFolder = Join-Path $PSScriptRoot 'obj' + +$isAzure = [System.Convert]::ToBoolean('true') + +if(-not $Debugger) { + Write-Host -ForegroundColor Green 'Cleaning build folders...' + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path $binFolder, $objFolder + + if((Test-Path $binFolder) -or (Test-Path $objFolder)) { + Write-Host -ForegroundColor Cyan 'Did you forget to exit your isolated module session before rebuilding?' + Write-Error 'Unable to clean ''bin'' or ''obj'' folder. A process may have an open handle.' + } + + Write-Host -ForegroundColor Green 'Compiling module...' + $buildConfig = 'Debug' + if($Release) { + $buildConfig = 'Release' + } + dotnet publish $PSScriptRoot --verbosity quiet --configuration $buildConfig /nologo + if($LastExitCode -ne 0) { + Write-Error 'Compilation failed.' + } + + $null = Remove-Item -Recurse -ErrorAction SilentlyContinue -Path (Join-Path $binFolder 'Debug'), (Join-Path $binFolder 'Release') +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Qumulo.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.Qumulo.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.Qumulo.psd1' +$guid = Get-ModuleGuid -Psd1Path $psd1 +$moduleName = 'Az.Qumulo' +$examplesFolder = Join-Path $PSScriptRoot 'examples' +$null = New-Item -ItemType Directory -Force -Path $examplesFolder + +Write-Host -ForegroundColor Green 'Creating cmdlets for specified models...' +$modelCmdlets = @() +$modelCmdletFolder = Join-Path (Join-Path $PSScriptRoot './custom') 'autogen-model-cmdlets' +if (Test-Path $modelCmdletFolder) { + $null = Remove-Item -Force -Recurse -Path $modelCmdletFolder +} +if ($modelCmdlets.Count -gt 0) { + . (Join-Path $PSScriptRoot 'create-model-cmdlets.ps1') + CreateModelCmdlet($modelCmdlets) +} + +if($NoDocs) { + Write-Host -ForegroundColor Green 'Creating exports...' + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ExcludeDocs -ExamplesFolder $examplesFolder +} else { + Write-Host -ForegroundColor Green 'Creating exports and docs...' + $moduleDescription = 'Microsoft Azure PowerShell: Qumulo cmdlets' + $docsFolder = Join-Path $PSScriptRoot 'docs' + if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue + } + $null = New-Item -ItemType Directory -Force -Path $docsFolder + $addComplexInterfaceInfo = !$isAzure + Export-ProxyCmdlet -ModuleName $moduleName -ModulePath $modulePaths -ExportsFolder $exportsFolder -InternalFolder $internalFolder -ModuleDescription $moduleDescription -DocsFolder $docsFolder -ExamplesFolder $examplesFolder -ModuleGuid $guid -AddComplexInterfaceInfo:$addComplexInterfaceInfo +} + +Write-Host -ForegroundColor Green 'Creating format.ps1xml...' +$formatPs1xml = Join-Path $PSScriptRoot './Az.Qumulo.format.ps1xml' +Export-FormatPs1xml -FilePath $formatPs1xml + +Write-Host -ForegroundColor Green 'Creating psd1...' +$customFolder = Join-Path $PSScriptRoot 'custom' +Export-Psd1 -ExportsFolder $exportsFolder -CustomFolder $customFolder -Psd1Path $psd1 -ModuleGuid $guid + +Write-Host -ForegroundColor Green 'Creating test stubs...' +$testFolder = Join-Path $PSScriptRoot 'test' +$null = New-Item -ItemType Directory -Force -Path $testFolder +Export-TestStub -ModuleName $moduleName -ExportsFolder $exportsFolder -OutputFolder $testFolder + +Write-Host -ForegroundColor Green 'Creating example stubs...' +Export-ExampleStub -ExportsFolder $exportsFolder -OutputFolder $examplesFolder + +if (Test-Path (Join-Path $PSScriptRoot 'generate-portal-ux.ps1')) +{ + Write-Host -ForegroundColor Green 'Creating ux metadata...' + . (Join-Path $PSScriptRoot 'generate-portal-ux.ps1') +} + +if (-not $DisableAfterBuildTasks){ + $afterBuildTasksPath = Join-Path $PSScriptRoot '' + $afterBuildTasksArgs = ConvertFrom-Json 'true' -AsHashtable + if(Test-Path -Path $afterBuildTasksPath -PathType leaf){ + Write-Host -ForegroundColor Green 'Running after build tasks...' + . $afterBuildTasksPath @afterBuildTasksArgs + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/check-dependencies.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/check-dependencies.ps1 new file mode 100644 index 00000000000..90ca9867ae4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/check-dependencies.ps1 @@ -0,0 +1,65 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Accounts, [switch]$Pester, [switch]$Resources) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +function DownloadModule ([bool]$predicate, [string]$path, [string]$moduleName, [string]$versionMinimum, [string]$requiredVersion) { + if($predicate) { + $module = Get-Module -ListAvailable -Name $moduleName + if((-not $module) -or ($versionMinimum -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -ge [System.Version]$versionMinimum } | Measure-Object).Count -eq 0) -or ($requiredVersion -and ($module | ForEach-Object { $_.Version } | Where-Object { $_ -eq [System.Version]$requiredVersion } | Measure-Object).Count -eq 0)) { + $null = New-Item -ItemType Directory -Force -Path $path + Write-Host -ForegroundColor Green "Installing local $moduleName module into '$path'..." + if ($requiredVersion) { + Find-Module -Name $moduleName -RequiredVersion $requiredVersion -Repository PSGallery | Save-Module -Path $path + }elseif($versionMinimum) { + Find-Module -Name $moduleName -MinimumVersion $versionMinimum -Repository PSGallery | Save-Module -Path $path + } else { + Find-Module -Name $moduleName -Repository PSGallery | Save-Module -Path $path + } + } + } +} + +$ProgressPreference = 'SilentlyContinue' +$all = (@($Accounts.IsPresent, $Pester.IsPresent) | Select-Object -Unique | Measure-Object).Count -eq 1 + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +DownloadModule -predicate ($all -or $Accounts) -path $localModulesPath -moduleName 'Az.Accounts' -versionMinimum '2.7.5' +DownloadModule -predicate ($all -or $Pester) -path $localModulesPath -moduleName 'Pester' -requiredVersion '4.10.1' + +$tools = Join-Path $PSScriptRoot 'tools' +$resourceDir = Join-Path $tools 'Resources' +$resourceModule = Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psm1' + +if ($Resources.IsPresent -and ((-not (Test-Path -Path $resourceModule)) -or $RegenerateSupportModule.IsPresent)) { + Write-Host -ForegroundColor Green "Building local Resource module used for test..." + Set-Location $resourceDir + $null = autorest .\README.md --use:@autorest/powershell@3.0.414 --output-folder=$HOME/.PSSharedModules/Resources + $null = Copy-Item custom/* $HOME/.PSSharedModules/Resources/custom/ + Set-Location $HOME/.PSSharedModules/Resources + $null = .\build-module.ps1 + Set-Location $PSScriptRoot +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/create-model-cmdlets.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/create-model-cmdlets.ps1 new file mode 100644 index 00000000000..6c5828b78e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/create-model-cmdlets.ps1 @@ -0,0 +1,262 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +function CreateModelCmdlet { + + param([Hashtable[]]$Models) + + if ($Models.Count -eq 0) + { + return + } + + $ModelCsPath = Join-Path (Join-Path $PSScriptRoot 'generated\api') 'Models' + $OutputDir = Join-Path $PSScriptRoot 'custom\autogen-model-cmdlets' + $null = New-Item -ItemType Directory -Force -Path $OutputDir + if (''.length -gt 0) { + $ModuleName = '' + } else { + $ModuleName = 'Az.Qumulo' + } + $CsFiles = Get-ChildItem -Path $ModelCsPath -Recurse -Filter *.cs + $Content = '' + $null = $CsFiles | ForEach-Object -Process { if ($_.Name.Split('.').count -eq 2 ) + { $Content += get-content $_.fullname -raw + } } + + $Tree = [Microsoft.CodeAnalysis.CSharp.SyntaxFactory]::ParseCompilationUnit($Content) + $Nodes = $Tree.ChildNodes().ChildNodes() + $classConstantMember = @{} + foreach ($Model in $Models) + { + $ModelName = $Model.modelName + $InterfaceNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq "I$ModelName") } + $ClassNode = $Nodes | Where-Object { ($_.Keyword.value -eq 'class') -and ($_.Identifier.value -eq "$ModelName") } + $classConstantMember = @() + foreach ($class in $ClassNode) { + foreach ($member in $class.Members) { + $isConstant = $false + foreach ($attr in $member.AttributeLists) { + $memberName = $attr.Attributes.Name.ToString() + if ($memberName.EndsWith('.Constant')) { + $isConstant = $true + break + } + } + if (($member.Modifiers.ToString() -eq 'public') -and $isConstant) { + $classConstantMember += $member.Identifier.Value + } + } + } + if ($InterfaceNode.count -eq 0) { + continue + } + # through a queue, we iterate all the parent models. + $Queue = @($InterfaceNode) + $visited = @("I$ModelName") + $AllInterfaceNodes = @() + while ($Queue.count -ne 0) + { + $AllInterfaceNodes += $Queue[0] + # Baselist contains the direct parent models. + foreach ($parent in $Queue[0].BaseList.Types) + { + if (($parent.Type.Right.Identifier.Value -ne 'IJsonSerializable') -and (-not $visited.Contains($parent.Type.Right.Identifier.Value))) + { + $Queue = [Array]$Queue + ($Nodes | Where-Object { ($_.Keyword.value -eq 'interface') -and ($_.Identifier.value -eq $parent.Type.Right.Identifier.Value) }) + $visited = [Array]$visited + $parent.Type.Right.Identifier.Value + } + } + $first, $Queue = $Queue + } + + $Namespace = $InterfaceNode.Parent.Name + $ObjectType = $ModelName + $ObjectTypeWithNamespace = "${Namespace}.${ObjectType}" + # remove duplicated module name + if ($ObjectType.StartsWith('Qumulo')) { + $ModulePrefix = '' + } else { + $ModulePrefix = 'Qumulo' + } + $OutputPath = Join-Path -ChildPath "New-Az${ModulePrefix}${ObjectType}Object.ps1" -Path $OutputDir + + $ParameterDefineScriptList = New-Object System.Collections.Generic.List[string] + $ParameterAssignScriptList = New-Object System.Collections.Generic.List[string] + foreach ($Node in $AllInterfaceNodes) + { + foreach ($Member in $Node.Members) + { + if ($classConstantMember.Contains($Member.Identifier.Value)) { + # skip constant member + continue + } + $Arguments = $Member.AttributeLists.Attributes.ArgumentList.Arguments + $Required = $false + $Description = "" + $Readonly = $False + $mutability = @{Read = $true; Create = $true; Update = $true} + foreach ($Argument in $Arguments) + { + if ($Argument.NameEquals.Name.Identifier.Value -eq "Required") + { + $Required = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Description") + { + $Description = $Argument.Expression.Token.Value.Trim('.').replace('"', '`"') + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Readonly") + { + $Readonly = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Read") + { + $mutability.Read = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Create") + { + $mutability.Create = $Argument.Expression.Token.Value + } + if ($Argument.NameEquals.Name.Identifier.Value -eq "Update") + { + $mutability.Update = $Argument.Expression.Token.Value + } + } + if ($Readonly) + { + continue + } + $Identifier = $Member.Identifier.Value + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + $Type = $Member.Type.ToString().replace('?', '').Split("::")[-1] + if ($Type.StartsWith("System.Collections.Generic.List")) + { + # if the type is a list, we need to convert it to array + $matched = $Type -match '\<(?.+)\>$' + if ($matched) + { + $Type = $matches.Name + '[]'; + } + } + $ParameterDefinePropertyList = New-Object System.Collections.Generic.List[string] + if ($Required -and $mutability.Create -and $mutability.Update) + { + $ParameterDefinePropertyList.Add("Mandatory") + } + if ($Description -ne "") + { + $ParameterDefinePropertyList.Add("HelpMessage=`"${Description}.`"") + } + $ParameterDefineProperty = [System.String]::Join(", ", $ParameterDefinePropertyList) + # check whether completer is needed + $completer = ''; + if(IsEnumType($Member)){ + $completer += GetCompleter($Member) + } + $ParameterDefineScript = " + [Parameter($ParameterDefineProperty)]${completer} + [${Type}] + `$${Identifier}" + $ParameterDefineScriptList.Add($ParameterDefineScript) + $ParameterAssignScriptList.Add(" + if (`$PSBoundParameters.ContainsKey('${Identifier}')) { + `$Object.${Identifier} = `$${Identifier} + }") + } + } + $ParameterDefineScript = $ParameterDefineScriptList | Join-String -Separator "," + $ParameterAssignScript = $ParameterAssignScriptList | Join-String -Separator "" + + $cmdletName = "New-Az${ModulePrefix}${ObjectType}Object" + if ('' -ne $Model.cmdletName) { + $cmdletName = $Model.cmdletName + } + $OutputPath = Join-Path -ChildPath "${cmdletName}.ps1" -Path $OutputDir + $cmdletNameInLowerCase = $cmdletName.ToLower() + $Script = " +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- + +<# +.Synopsis +Create an in-memory object for ${ObjectType}. +.Description +Create an in-memory object for ${ObjectType}. + +.Outputs +${ObjectTypeWithNamespace} +.Link +https://learn.microsoft.com/powershell/module/${ModuleName}/${cmdletNameInLowerCase} +#> +function ${cmdletName} { + [OutputType('${ObjectTypeWithNamespace}')] + [CmdletBinding(PositionalBinding=`$false)] + Param( +${ParameterDefineScript} + ) + + process { + `$Object = [${ObjectTypeWithNamespace}]::New() +${ParameterAssignScript} + return `$Object + } +} +" + Set-Content -Path $OutputPath -Value $Script + } +} + +function IsEnumType { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + $isEnum = $false + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $isEnum = $true + break + } + } + return $isEnum; +} + +function GetCompleter { + param ( + [Microsoft.CodeAnalysis.CSharp.Syntax.PropertyDeclarationSyntax]$property + ) + foreach ($attr in $property.AttributeLists) { + $attributeName = $attr.Attributes.Name.ToString() + if ($attributeName.Contains('ArgumentCompleter')) { + $attributeName = $attributeName.Split("::")[-1] + $possibleValues = [System.String]::Join(", ", $attr.Attributes.ArgumentList.Arguments) + $completer += "`n [${attributeName}(${possibleValues})]" + return $completer + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/Az.Qumulo.custom.psm1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/Az.Qumulo.custom.psm1 new file mode 100644 index 00000000000..2e0fba135e2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/Az.Qumulo.custom.psm1 @@ -0,0 +1,17 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Qumulo.private.dll') + + # Load the internal module + $internalModulePath = Join-Path $PSScriptRoot '..\internal\Az.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/README.md new file mode 100644 index 00000000000..a9b25d49110 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/custom/README.md @@ -0,0 +1,41 @@ +# Custom +This directory contains custom implementation for non-generated cmdlets for the `Az.Qumulo` 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.Qumulo.custom.psm1`. This file should not be modified. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: yes + +## Details +For `Az.Qumulo` 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.Qumulo.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.Qumulo.custom.psm1`. Then, during the build process, this module is loaded and processed in the same manner as the C# cmdlets. The fundamental difference is the script cmdlets use the `ParameterSetName` attribute and C# cmdlets do not. To create a script cmdlet variant of a generated cmdlet, simply decorate all parameters in the script with the new `ParameterSetName` in the `Parameter` attribute. This will appropriately treat each parameter set as a separate variant when processed to be exported during the build. + +## Purpose +This allows the modules to have cmdlets that were not defined in the REST specification. It also allows combining logic using generated cmdlets. This is a level of customization beyond what can be done using the [readme configuration options](https://github.com/Azure/autorest/blob/master/docs/powershell/options.md) that are currently available. These custom cmdlets are then referenced by the cmdlets created at build-time in the `..\exports` folder. + +## Usage +The easiest way currently to start developing custom cmdlets is to copy an existing cmdlet. For C# cmdlets, copy one from the `generated/cmdlets` folder. For script cmdlets, build the project using `build-module.ps1` and copy one of the scripts from the `..\exports` folder. After that, if you want to add new parameter sets, follow the guidelines in the `Details` section above. For implementing a new cmdlets, at minimum, please keep these parameters: +- Break +- DefaultProfile +- HttpPipelineAppend +- HttpPipelinePrepend +- Proxy +- ProxyCredential +- ProxyUseDefaultCredentials + +These provide functionality to our HTTP pipeline and other useful features. In script, you can forward these parameters using `$PSBoundParameters` to the other cmdlets you're calling within `Az.Qumulo`. 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.Qumulo.DescriptionAttribute` + - Used in C# cmdlets to provide a high-level description of the cmdlet. This is propagated to reference documentation via [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) in the exported scripts. +- `Microsoft.Azure.PowerShell.Cmdlets.Qumulo.DoNotExportAttribute` + - Used in C# and script cmdlets to suppress creating an exported cmdlet at build-time. These cmdlets will *not be exposed* by `Az.Qumulo`. +- `Microsoft.Azure.PowerShell.Cmdlets.Qumulo.InternalExportAttribute` + - Used in C# cmdlets to route exported cmdlets to the `..\internal`, which are *not exposed* by `Az.Qumulo`. For more information, see [README.md](..\internal/README.md) in the `..\internal` folder. +- `Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/docs/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/docs/README.md new file mode 100644 index 00000000000..88fb0c7df70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Qumulo` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overridden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Qumulo` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/examples/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/export-surface.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/export-surface.ps1 new file mode 100644 index 00000000000..34ff172b000 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/export-surface.ps1 @@ -0,0 +1,41 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$IncludeGeneralParameters, [switch]$UseExpandedFormat) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$dll = Join-Path $PSScriptRoot 'bin\Az.Qumulo.private.dll' +if(-not (Test-Path $dll)) { + Write-Error "Unable to find output assembly in '$binFolder'." +} +$null = Import-Module -Name $dll + +$moduleName = 'Az.Qumulo' +$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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/exports/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/exports/README.md new file mode 100644 index 00000000000..da39080669a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/exports/README.md @@ -0,0 +1,20 @@ +# Exports +This directory contains the cmdlets *exported by* `Az.Qumulo`. No other cmdlets in this repository are directly exported. What that means is the `Az.Qumulo` module will run [Export-ModuleMember](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember) on the cmldets in this directory. The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The cmdlets generated here are created every time you run `build-module.ps1`. These cmdlets are a merge of all (excluding `InternalExport`) cmdlets from the private binary (`..\bin\Az.Qumulo.private.dll`) and from the `..\custom\Az.Qumulo.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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-help.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-help.ps1 new file mode 100644 index 00000000000..b8f066d8585 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-help.ps1 @@ -0,0 +1,74 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$exportsFolder = Join-Path $PSScriptRoot 'exports' +if(-not (Test-Path $exportsFolder)) { + Write-Error "Exports folder '$exportsFolder' was not found." +} + +$directories = Get-ChildItem -Directory -Path $exportsFolder +$hasProfiles = ($directories | Measure-Object).Count -gt 0 +if(-not $hasProfiles) { + $directories = Get-Item -Path $exportsFolder +} + +$docsFolder = Join-Path $PSScriptRoot 'docs' +if(Test-Path $docsFolder) { + $null = Get-ChildItem -Path $docsFolder -Recurse -Exclude 'README.md' | Remove-Item -Recurse -ErrorAction SilentlyContinue +} +$null = New-Item -ItemType Directory -Force -Path $docsFolder -ErrorAction SilentlyContinue +$examplesFolder = Join-Path $PSScriptRoot 'examples' + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Qumulo.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.Qumulo.private.dll') +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName + +foreach($directory in $directories) +{ + if($hasProfiles) { + Select-AzProfile -Name $directory.Name + } + # Reload module per profile + Import-Module -Name $modulePath -Force + + $cmdletNames = Get-ScriptCmdlet -ScriptFolder $directory.FullName + $cmdletHelpInfo = $cmdletNames | ForEach-Object { Get-Help -Name $_ -Full } + $cmdletFunctionInfo = Get-ScriptCmdlet -ScriptFolder $directory.FullName -AsFunctionInfo + + $docsPath = Join-Path $docsFolder $directory.Name + $null = New-Item -ItemType Directory -Force -Path $docsPath -ErrorAction SilentlyContinue + $examplesPath = Join-Path $examplesFolder $directory.Name + $addComplexInterfaceInfo = ![System.Convert]::ToBoolean('true') + Export-HelpMarkdown -ModuleInfo $moduleInfo -FunctionInfo $cmdletFunctionInfo -HelpInfo $cmdletHelpInfo -DocsFolder $docsPath -ExamplesFolder $examplesPath -AddComplexInterfaceInfo:$addComplexInterfaceInfo + Write-Host -ForegroundColor Green "Created documentation in '$docsPath'" +} + +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-portal-ux.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-portal-ux.ps1 new file mode 100644 index 00000000000..37984bf837d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generate-portal-ux.ps1 @@ -0,0 +1,383 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# +# This Script will create a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +# These files are utilized by the Azure portal to effectively present the usage of cmdlets related to specific resources on portal pages. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated) +$ErrorActionPreference = 'Stop' + +$pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$moduleName = 'Az.Qumulo' +$rootModuleName = '' +if ($rootModuleName -eq "") +{ + $rootModuleName = $moduleName +} +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot "./$moduleName.psd1") +$modulePath = $modulePsd1.FullName + +# Load DLL to use build-time cmdlets +Import-Module -Name $modulePath +Import-Module -Name (Join-Path $PSScriptRoot "./bin/$moduleName.private.dll") +$instance = [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module]::Instance +# Module info is shared per profile +$moduleInfo = Get-Module -Name $moduleName +$parameterSetsInfo = Get-Module -Name "$moduleName.private" + +function Test-FunctionSupported() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + If (-not $FunctionName.Contains("_")) { + return $false + } + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + If ($parameterSetName.Contains("List") -or $parameterSetName.Contains("ViaIdentity") -or $parameterSetName.Contains("ViaJson")) { + return $false + } + If ($cmdletName.StartsWith("New") -or $cmdletName.StartsWith("Set") -or $cmdletName.StartsWith("Update")) { + return $false + } + + $parameterSetInfo = $parameterSetsInfo.ExportedCmdlets[$FunctionName] + foreach ($parameterInfo in $parameterSetInfo.Parameters.Values) + { + $category = (Get-ParameterAttribute -ParameterInfo $parameterInfo -AttributeName "CategoryAttribute").Categories + $invalideCategory = @('Query', 'Body') + if ($invalideCategory -contains $category) + { + return $false + } + } + + $customFiles = Get-ChildItem -Path custom -Filter "$cmdletName.*" + if ($customFiles.Length -ne 0) + { + Write-Host -ForegroundColor Yellow "There are come custom files for $cmdletName, skip generate UX data for it." + return $false + } + + return $true +} + +function Get-MappedCmdletFromFunctionName() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [string] + $FunctionName + ) + + $cmdletName, $parameterSetName = $FunctionName.Split("_") + + return $cmdletName +} + +function Get-ParameterAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo, + [Parameter()] + [String] + $AttributeName + ) + return $ParameterInfo.Attributes | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletAttribute() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $CmdletInfo, + [Parameter()] + [String] + $AttributeName + ) + + return $CmdletInfo.ImplementingType.GetTypeInfo().GetCustomAttributes([System.object], $true) | Where-Object { $_.TypeId.Name -eq $AttributeName } +} + +function Get-CmdletDescription() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [String] + $CmdletName + ) + $helpInfo = Get-Help $CmdletName -Full + + $description = $helpInfo.Description.Text + if ($null -eq $description) + { + return "" + } + return $description +} + +# Test whether the parameter is from swagger http path +function Test-ParameterFromSwagger() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.ParameterMetadata] + $ParameterInfo + ) + $category = (Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "CategoryAttribute").Categories + $doNotExport = Get-ParameterAttribute -ParameterInfo $ParameterInfo -AttributeName "DoNotExportAttribute" + if ($null -ne $doNotExport) + { + return $false + } + + $valideCategory = @('Path') + if ($valideCategory -contains $category) + { + return $true + } + return $false +} + +function New-ExampleForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $category = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "CategoryAttribute").Categories + $sourceName = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "InfoAttribute").SerializedName + $name = $parameter.Name + $result += [ordered]@{ + name = "-$Name" + value = "[$category.$sourceName]" + } + } + + return $result +} + +function New-ParameterArrayInParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $parameters = $ParameterSetInfo.Parameters.Values | Where-Object { Test-ParameterFromSwagger $_ } + $result = @() + foreach ($parameter in $parameters) + { + $isMandatory = (Get-ParameterAttribute -parameterInfo $parameter -AttributeName "ParameterAttribute").Mandatory + $parameterName = $parameter.Name + $parameterType = $parameter.ParameterType.ToString().Split('.')[1] + if ($parameter.SwitchParameter) + { + $parameterSignature = "-$parameterName" + } + else + { + $parameterSignature = "-$parameterName <$parameterType>" + } + if ($parameterName -eq "SubscriptionId") + { + $isMandatory = $false + } + if (-not $isMandatory) + { + $parameterSignature = "[$parameterSignature]" + } + $result += $parameterSignature + } + + return $result +} + +function New-MetadataForParameterSet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Management.Automation.CommandInfo] + $ParameterSetInfo + ) + $httpAttribute = Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "HttpPathAttribute" + $httpPath = $httpAttribute.Path + $apiVersion = $httpAttribute.ApiVersion + $provider = [System.Text.RegularExpressions.Regex]::New("/providers/([\w+\.]+)/").Match($httpPath).Groups[1].Value + $resourcePath = "/" + $httpPath.Split("$provider/")[1] + $resourceType = [System.Text.RegularExpressions.Regex]::New("/([\w]+)/\{\w+\}").Matches($resourcePath) | ForEach-Object {$_.groups[1].Value} | Join-String -Separator "/" + $cmdletName = Get-MappedCmdletFromFunctionName $ParameterSetInfo.Name + $description = (Get-CmdletAttribute -CmdletInfo $ParameterSetInfo -AttributeName "DescriptionAttribute").Description + [object[]]$example = New-ExampleForParameterSet $ParameterSetInfo + if ($Null -eq $example) + { + $example = @() + } + + [string[]]$signature = New-ParameterArrayInParameterSet $ParameterSetInfo + if ($Null -eq $signature) + { + $signature = @() + } + + return @{ + Path = $httpPath + Provider = $provider + ResourceType = $resourceType + ApiVersion = $apiVersion + CmdletName = $cmdletName + Description = $description + Example = $example + Signature = @{ + parameters = $signature + } + } +} + +function Merge-WithExistCmdletMetadata() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [System.Collections.Specialized.OrderedDictionary] + $ExistedCmdletInfo, + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $ExistedCmdletInfo.help.parameterSets += $ParameterSetMetadata.Signature + $ExistedCmdletInfo.examples += [ordered]@{ + description = $ParameterSetMetadata.Description + parameters = $ParameterSetMetadata.Example + } + + return $ExistedCmdletInfo +} + +function New-MetadataForCmdlet() +{ + [CmdletBinding()] + Param ( + [Parameter()] + [Hashtable] + $ParameterSetMetadata + ) + $cmdletName = $ParameterSetMetadata.CmdletName + $description = Get-CmdletDescription $cmdletName + $result = [ordered]@{ + name = $cmdletName + description = $description + path = $ParameterSetMetadata.Path + help = [ordered]@{ + learnMore = [ordered]@{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName/$cmdletName".ToLower() + } + parameterSets = @() + } + examples = @() + } + $result = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $result -ParameterSetMetadata $ParameterSetMetadata + return $result +} + +$parameterSets = $parameterSetsInfo.ExportedCmdlets.Keys | Where-Object { Test-FunctionSupported($_) } +$resourceTypes = @{} +foreach ($parameterSetName in $parameterSets) +{ + $cmdletInfo = $parameterSetsInfo.ExportedCommands[$parameterSetName] + $parameterSetMetadata = New-MetadataForParameterSet -ParameterSetInfo $cmdletInfo + $cmdletName = $parameterSetMetadata.CmdletName + if (-not ($moduleInfo.ExportedCommands.ContainsKey($cmdletName))) + { + continue + } + if ($resourceTypes.ContainsKey($parameterSetMetadata.ResourceType)) + { + $ExistedCmdletInfo = $resourceTypes[$parameterSetMetadata.ResourceType].commands | Where-Object { $_.name -eq $cmdletName } + if ($ExistedCmdletInfo) + { + $ExistedCmdletInfo = Merge-WithExistCmdletMetadata -ExistedCmdletInfo $ExistedCmdletInfo -ParameterSetMetadata $parameterSetMetadata + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType].commands += $cmdletInfo + } + } + else + { + $cmdletInfo = New-MetadataForCmdlet -ParameterSetMetadata $parameterSetMetadata + $resourceTypes[$parameterSetMetadata.ResourceType] = [ordered]@{ + resourceType = $parameterSetMetadata.ResourceType + apiVersion = $parameterSetMetadata.ApiVersion + learnMore = @{ + url = "https://learn.microsoft.com/powershell/module/$rootModuleName".ToLower() + } + commands = @($cmdletInfo) + provider = $parameterSetMetadata.Provider + } + } +} + +$UXFolder = 'UX' +if (Test-Path $UXFolder) +{ + Remove-Item -Path $UXFolder -Recurse +} +$null = New-Item -ItemType Directory -Path $UXFolder + +foreach ($resourceType in $resourceTypes.Keys) +{ + $resourceTypeFileName = $resourceType -replace "/", "-" + if ($resourceTypeFileName -eq "") + { + continue + } + $resourceTypeInfo = $resourceTypes[$resourceType] + $provider = $resourceTypeInfo.provider + $providerFolder = "$UXFolder/$provider" + if (-not (Test-Path $providerFolder)) + { + $null = New-Item -ItemType Directory -Path $providerFolder + } + $resourceTypeInfo.Remove("provider") + $resourceTypeInfo | ConvertTo-Json -Depth 10 | Out-File "$providerFolder/$resourceTypeFileName.json" +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/Module.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/Module.cs new file mode 100644 index 00000000000..466b503efe6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/Module.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using SendAsyncStepDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using PipelineChangeDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>; + using GetParameterDelegate = global::System.Func; + using ModuleLoadPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using ArgumentCompleterDelegate = global::System.Func; + using GetTelemetryIdDelegate = global::System.Func; + using TelemetryDelegate = global::System.Action; + using NewRequestPipelineDelegate = global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>, global::System.Action, global::System.Threading.Tasks.Task>, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>>>; + using SignalDelegate = global::System.Func, global::System.Threading.Tasks.Task>; + using EventListenerDelegate = global::System.Func, global::System.Func, global::System.Threading.Tasks.Task>, global::System.Management.Automation.InvocationInfo, string, string, string, global::System.Exception, global::System.Threading.Tasks.Task>; + using NextDelegate = global::System.Func, global::System.Threading.Tasks.Task>, global::System.Threading.Tasks.Task>; + using SanitizerDelegate = global::System.Action; + using GetTelemetryInfoDelegate = global::System.Func>; + + /// A class that contains the module-common code and data. + public partial class Module + { + /// The currently selected profile. + public string Profile = global::System.String.Empty; + + public global::System.Net.Http.HttpClientHandler _handler = new global::System.Net.Http.HttpClientHandler(); + + private static bool _init = false; + + private static readonly global::System.Object _initLock = new global::System.Object(); + + private static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module _instance; + + /// the ISendAsync pipeline instance + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline _pipeline; + + /// the ISendAsync pipeline instance (when proxy is enabled) + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline _pipelineWithProxy; + + private static readonly global::System.Object _singletonLock = new global::System.Object(); + + public bool _useProxy = false; + + public global::System.Net.WebProxy _webProxy = new global::System.Net.WebProxy(); + + /// Gets completion data for azure specific fields + public ArgumentCompleterDelegate ArgumentCompleter { get; set; } + + /// The instance of the Client API + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage ClientAPI { get; set; } + + /// A delegate that gets called for each signalled event + public EventListenerDelegate EventListener { get; set; } + + /// The delegate to call to get parameter data from a common module. + public GetParameterDelegate GetParameterValue { get; set; } + + /// The delegate to get the telemetry Id. + public GetTelemetryIdDelegate GetTelemetryId { get; set; } + + /// The delegate to get the telemetry info. + public GetTelemetryInfoDelegate GetTelemetryInfo { get; set; } + + /// the singleton of this module class + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module Instance { get { if (_instance == null) { lock (_singletonLock) { if (_instance == null) { _instance = new Module(); }}} return _instance; } } + + /// The Name of this module + public string Name => @"Az.Qumulo"; + + /// 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.Qumulo"; + + /// The delegate to call in WriteObject to sanitize the output object. + public SanitizerDelegate SanitizeOutput { get; set; } + + /// The delegate for creating a telemetry. + public TelemetryDelegate Telemetry { get; set; } + + /// The from the cmdlet + /// The HttpPipeline for the request + + partial void AfterCreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.HttpPipeline pipeline); + + partial void CustomInit(); + + /// Creates an instance of the HttpPipeline for each call. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the cmdlet's parameterset name. + /// a dict for extensible parameters + /// An instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline for the remote call. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline CreatePipeline(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string processRecordId, string parameterSetName = null, global::System.Collections.Generic.IDictionary extensibleParameters = null) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline pipeline = null; + BeforeCreatePipeline(invocationInfo, ref pipeline); + pipeline = (pipeline ?? (_useProxy ? _pipelineWithProxy : _pipeline)).Clone(); + AfterCreatePipeline(invocationInfo, ref pipeline); + pipeline.Append(new Runtime.CmdInfoHandler(processRecordId, invocationInfo, parameterSetName).SendAsync); + OnNewRequest?.Invoke( invocationInfo, correlationId,processRecordId, (step)=> { pipeline.Prepend(step); } , (step)=> { pipeline.Append(step); } ); + return pipeline; + } + + /// Gets parameters from a common module. + /// The from the cmdlet + /// the cmdlet's correlation id. + /// The name of the parameter to get the value for. + /// + /// The parameter value from the common module. (Note: this should be type converted on the way back) + /// + public object GetParameter(global::System.Management.Automation.InvocationInfo invocationInfo, string correlationId, string parameterName) => GetParameterValue?.Invoke( ResourceId, Name, invocationInfo, correlationId,parameterName ); + + /// Initialization steps performed after the module is loaded. + public void Init() + { + if (_init == false) + { + lock (_initLock) { + if (_init == false) { + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipeline.Prepend(step); } , (step)=> { _pipeline.Append(step); } ); + OnModuleLoad?.Invoke( ResourceId, Name ,(step)=> { _pipelineWithProxy.Prepend(step); } , (step)=> { _pipelineWithProxy.Append(step); } ); + CustomInit(); + _init = true; + } + } + } + } + + /// Creates the module instance. + private Module() + { + // constructor + ClientAPI = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage(); + _handler.Proxy = _webProxy; + _pipeline = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient())); + _pipelineWithProxy = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline(new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpClientFactory(new global::System.Net.Http.HttpClient(_handler))); + } + + /// The HTTP Proxy to use. + /// The HTTP Proxy Credentials + /// True if the proxy should use default credentials + public void SetProxyConfiguration(global::System.Uri proxy, global::System.Management.Automation.PSCredential proxyCredential, bool proxyUseDefaultCredentials) + { + _useProxy = proxy != null; + if (proxy == null) + { + return; + } + // set the proxy configuration + _webProxy.Address = proxy; + _webProxy.BypassProxyOnLocal = false; + if (proxyUseDefaultCredentials) + { + _webProxy.Credentials = null; + _webProxy.UseDefaultCredentials = true; + } + else + { + _webProxy.UseDefaultCredentials = false; + _webProxy.Credentials = proxyCredential ?.GetNetworkCredential(); + } + } + + /// Called to dispatch events to the common module listener + /// The ID of the event + /// The cancellation token for the event + /// A delegate to get the detailed event data + /// The callback for the event dispatcher + /// The from the cmdlet + /// the cmdlet's parameterset name. + /// the cmdlet's correlation id. + /// the cmdlet's process record correlation id. + /// the exception that is being thrown (if available) + /// + /// A that will be complete when handling of the event is completed. + /// + public async global::System.Threading.Tasks.Task Signal(string id, global::System.Threading.CancellationToken token, global::System.Func getEventData, SignalDelegate signal, global::System.Management.Automation.InvocationInfo invocationInfo, string parameterSetName, string correlationId, string processRecordId, global::System.Exception exception) + { + using( NoSynchronizationContext ) + { + await EventListener?.Invoke(id,token,getEventData, signal, invocationInfo, parameterSetName, correlationId,processRecordId,exception); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.PowerShell.cs new file mode 100644 index 00000000000..6f6894040b8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.PowerShell.cs @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial class Any + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Any(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Any(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + AfterDeserializePSObject(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Any(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Any(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Anything + [System.ComponentModel.TypeConverter(typeof(AnyTypeConverter))] + public partial interface IAny + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.TypeConverter.cs new file mode 100644 index 00000000000..445184dc8d5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class AnyTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Any.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Any.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Any.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.cs new file mode 100644 index 00000000000..0ed077f97c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Anything + public partial class Any : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAnyInternal + { + + /// Creates an new instance. + public Any() + { + + } + } + /// Anything + public partial interface IAny : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + + } + /// Anything + internal partial interface IAnyInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.json.cs new file mode 100644 index 00000000000..4c02d6ba490 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Any.json.cs @@ -0,0 +1,102 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Anything + public partial class Any + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal Any(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new Any(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs new file mode 100644 index 00000000000..8f0bef00da8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial class ErrorAdditionalInfo + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorAdditionalInfo(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorAdditionalInfo(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorAdditionalInfo(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Info")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Info = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny) content.GetValueForProperty("Info",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal)this).Info, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.AnyTypeConverter.ConvertFrom); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The resource management error additional info. + [System.ComponentModel.TypeConverter(typeof(ErrorAdditionalInfoTypeConverter))] + public partial interface IErrorAdditionalInfo + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs new file mode 100644 index 00000000000..1f12ac4729d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorAdditionalInfoTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorAdditionalInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorAdditionalInfo.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.cs new file mode 100644 index 00000000000..165aa8fabbc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal + { + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny _info; + + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Any()); } + + /// Internal Acessors for Info + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal.Info { get => (this._info = this._info ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Any()); set { {_info = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfoInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _type; + + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public ErrorAdditionalInfo() + { + + } + } + /// The resource management error additional info. + public partial interface IErrorAdditionalInfo : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info.", + SerializedName = @"info", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny Info { get; } + /// The additional info type. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The additional info type.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// The resource management error additional info. + internal partial interface IErrorAdditionalInfoInternal + + { + /// The additional info. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IAny Info { get; set; } + /// The additional info type. + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.json.cs new file mode 100644 index 00000000000..d0a67afb96b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorAdditionalInfo.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The resource management error additional info. + public partial class ErrorAdditionalInfo + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorAdditionalInfo(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_info = If( json?.PropertyT("info"), out var __jsonInfo) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Any.FromJson(__jsonInfo) : _info;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new ErrorAdditionalInfo(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._info ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._info.ToJson(null,serializationMode) : null, "info" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs new file mode 100644 index 00000000000..26f3bf64681 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.PowerShell.cs @@ -0,0 +1,194 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial class ErrorDetail + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorDetail(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorDetail(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ErrorDetail(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Target, global::System.Convert.ToString); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + AfterDeserializePSObject(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The error detail. + [System.ComponentModel.TypeConverter(typeof(ErrorDetailTypeConverter))] + public partial interface IErrorDetail + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs new file mode 100644 index 00000000000..9929bfaa83d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorDetailTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorDetail.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorDetail.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.cs new file mode 100644 index 00000000000..17de84f9576 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal + { + + /// Backing field for property. + private System.Collections.Generic.List _additionalInfo; + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public System.Collections.Generic.List AdditionalInfo { get => this._additionalInfo; } + + /// Backing field for property. + private string _code; + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Code { get => this._code; } + + /// Backing field for property. + private System.Collections.Generic.List _detail; + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public System.Collections.Generic.List Detail { get => this._detail; } + + /// Backing field for property. + private string _message; + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Message { get => this._message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal.AdditionalInfo { get => this._additionalInfo; set { {_additionalInfo = value;} } } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal.Code { get => this._code; set { {_code = value;} } } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal.Detail { get => this._detail; set { {_detail = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal.Message { get => this._message; set { {_message = value;} } } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal.Target { get => this._target; set { {_target = value;} } } + + /// Backing field for property. + private string _target; + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Target { get => this._target; } + + /// Creates an new instance. + public ErrorDetail() + { + + } + } + /// The error detail. + public partial interface IErrorDetail : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// The error detail. + internal partial interface IErrorDetailInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.json.cs new file mode 100644 index 00000000000..cd5fdb50f95 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorDetail.json.cs @@ -0,0 +1,143 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The error detail. + public partial class ErrorDetail + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorDetail(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail) (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetail.FromJson(__u) )) ))() : null : _detail;} + {_additionalInfo = If( json?.PropertyT("additionalInfo"), out var __jsonAdditionalInfo) ? If( __jsonAdditionalInfo as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonArray, out var __q) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo) (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorAdditionalInfo.FromJson(__p) )) ))() : null : _additionalInfo;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new ErrorDetail(json) : null; + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._code)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._code.ToString()) : null, "code" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._message)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._message.ToString()) : null, "message" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._target)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._target.ToString()) : null, "target" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._detail) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.XNodeArray(); + foreach( var __x in this._detail ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("details",__w); + } + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + if (null != this._additionalInfo) + { + var __r = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.XNodeArray(); + foreach( var __s in this._additionalInfo ) + { + AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); + } + container.Add("additionalInfo",__r); + } + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs new file mode 100644 index 00000000000..068fb8bd52d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.PowerShell.cs @@ -0,0 +1,204 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial class ErrorResponse + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ErrorResponse(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ErrorResponse(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Target, 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 + if (content.Contains("Error")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Error = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail) content.GetValueForProperty("Error",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Error, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom); + } + if (content.Contains("Detail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Detail = (System.Collections.Generic.List) content.GetValueForProperty("Detail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Detail, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetailTypeConverter.ConvertFrom)); + } + if (content.Contains("AdditionalInfo")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).AdditionalInfo = (System.Collections.Generic.List) content.GetValueForProperty("AdditionalInfo",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).AdditionalInfo, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorAdditionalInfoTypeConverter.ConvertFrom)); + } + if (content.Contains("Code")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Code = (string) content.GetValueForProperty("Code",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Code, global::System.Convert.ToString); + } + if (content.Contains("Message")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Message = (string) content.GetValueForProperty("Message",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Message, global::System.Convert.ToString); + } + if (content.Contains("Target")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Target = (string) content.GetValueForProperty("Target",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal)this).Target, 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.Qumulo.Models.IErrorResponse FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + [System.ComponentModel.TypeConverter(typeof(ErrorResponseTypeConverter))] + public partial interface IErrorResponse + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs new file mode 100644 index 00000000000..0d3f4afa1c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ErrorResponseTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ErrorResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ErrorResponse.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.cs new file mode 100644 index 00000000000..9e737b689f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.cs @@ -0,0 +1,146 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + public partial class ErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal + { + + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public System.Collections.Generic.List AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).AdditionalInfo; } + + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Code; } + + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public System.Collections.Generic.List Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Detail; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail _error; + + /// The error object. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetail()); set => this._error = value; } + + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Message; } + + /// Internal Acessors for AdditionalInfo + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.AdditionalInfo { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).AdditionalInfo; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).AdditionalInfo = value; } + + /// Internal Acessors for Code + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.Code { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Code; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Code = value; } + + /// Internal Acessors for Detail + System.Collections.Generic.List Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.Detail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Detail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Detail = value; } + + /// Internal Acessors for Error + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.Error { get => (this._error = this._error ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorDetail()); set { {_error = value;} } } + + /// Internal Acessors for Message + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.Message { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Message; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Message = value; } + + /// Internal Acessors for Target + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponseInternal.Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Target; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Target = value; } + + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string Target { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetailInternal)Error).Target; } + + /// Creates an new instance. + public ErrorResponse() + { + + } + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + public partial interface IErrorResponse : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The error additional info. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error additional info.", + SerializedName = @"additionalInfo", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorAdditionalInfo) })] + System.Collections.Generic.List AdditionalInfo { get; } + /// The error code. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error code.", + SerializedName = @"code", + PossibleTypes = new [] { typeof(string) })] + string Code { get; } + /// The error details. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error details.", + SerializedName = @"details", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail) })] + System.Collections.Generic.List Detail { get; } + /// The error message. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error message.", + SerializedName = @"message", + PossibleTypes = new [] { typeof(string) })] + string Message { get; } + /// The error target. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The error target.", + SerializedName = @"target", + PossibleTypes = new [] { typeof(string) })] + string Target { get; } + + } + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + internal partial interface IErrorResponseInternal + + { + /// The error additional info. + System.Collections.Generic.List AdditionalInfo { get; set; } + /// The error code. + string Code { get; set; } + /// The error details. + System.Collections.Generic.List Detail { get; set; } + /// The error object. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorDetail Error { get; set; } + /// The error message. + string Message { get; set; } + /// The error target. + string Target { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.json.cs new file mode 100644 index 00000000000..198cb9e07aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ErrorResponse.json.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Common error response for all Azure Resource Manager APIs to return error details for failed operations. + /// + 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal ErrorResponse(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Models.ErrorDetail.FromJson(__jsonError) : _error;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._error ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.PowerShell.cs new file mode 100644 index 00000000000..dda8b486ade --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.PowerShell.cs @@ -0,0 +1,444 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceTypeConverter))] + public partial class FileSystemResource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemResource(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.Qumulo.Models.IFileSystemResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemResource(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemResource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StorageSku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).StorageSku = (string) content.GetValueForProperty("StorageSku",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).StorageSku, global::System.Convert.ToString); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ClusterLoginUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ClusterLoginUrl = (string) content.GetValueForProperty("ClusterLoginUrl",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ClusterLoginUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).PrivateIP = (System.Collections.Generic.List) content.GetValueForProperty("PrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).PrivateIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AdminPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AdminPassword = (string) content.GetValueForProperty("AdminPassword",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AdminPassword, global::System.Convert.ToString); + } + if (content.Contains("AvailabilityZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AvailabilityZone = (string) content.GetValueForProperty("AvailabilityZone",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AvailabilityZone, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetailEmail, 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 FileSystemResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourcePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StorageSku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).StorageSku = (string) content.GetValueForProperty("StorageSku",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).StorageSku, global::System.Convert.ToString); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ClusterLoginUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ClusterLoginUrl = (string) content.GetValueForProperty("ClusterLoginUrl",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).ClusterLoginUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).PrivateIP = (System.Collections.Generic.List) content.GetValueForProperty("PrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).PrivateIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AdminPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AdminPassword = (string) content.GetValueForProperty("AdminPassword",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AdminPassword, global::System.Convert.ToString); + } + if (content.Contains("AvailabilityZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AvailabilityZone = (string) content.GetValueForProperty("AvailabilityZone",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AvailabilityZone, global::System.Convert.ToString); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).UserDetailEmail, 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.Qumulo.Models.IFileSystemResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceTypeConverter))] + public partial interface IFileSystemResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.TypeConverter.cs new file mode 100644 index 00000000000..116355db264 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemResource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemResource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemResource.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.cs new file mode 100644 index 00000000000..0edd581bd22 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.cs @@ -0,0 +1,544 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + public partial class FileSystemResource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IValidates, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IHeaderSerializable + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TrackedResource(); + + /// Initial administrator password of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string AdminPassword { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).AdminPassword; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).AdminPassword = value ?? null; } + + /// Availability zone + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string AvailabilityZone { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).AvailabilityZone; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).AvailabilityZone = value ?? null; } + + /// Backing field for property. + private string _azureAsyncOperation; + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string AzureAsyncOperation { get => this._azureAsyncOperation; set => this._azureAsyncOperation = value; } + + /// File system Id of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string ClusterLoginUrl { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).ClusterLoginUrl; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).ClusterLoginUrl = value ?? null; } + + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DelegatedSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).DelegatedSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).DelegatedSubnetId = value ?? null; } + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Id; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity()); set => this._identity = value; } + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; } + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Location { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)__trackedResource).Location; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)__trackedResource).Location = value ; } + + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus; } + + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailOfferId = value ?? null; } + + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailPlanId = value ?? null; } + + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailPublisherId = value ?? null; } + + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailTermUnit = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId = value; } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.MarketplaceDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetail = value; } + + /// Internal Acessors for MarketplaceDetailMarketplaceSubscriptionStatus + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceProperties()); set { {_property = value;} } } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).ProvisioningState; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).ProvisioningState = value; } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal.UserDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).UserDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).UserDetail = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Name; } + + /// Private IPs of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public System.Collections.Generic.List PrivateIP { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).PrivateIP; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).PrivateIP = value ?? null /* arrayOf */; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties _property; + + /// The resource-specific properties for this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceProperties()); set => this._property = value; } + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string ProvisioningState { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).ProvisioningState; } + + /// Gets the resource group name + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string ResourceGroupName { get => (new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Success ? new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/resourceGroups/(?[^/]+)/providers/", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(this.Id).Groups["resourceGroupName"].Value : null); } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// Storage Sku + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string StorageSku { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).StorageSku; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).StorageSku = value ?? null; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).SystemDataLastModifiedByType = value ?? null; } + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)__trackedResource).Tag; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)__trackedResource).Tag = value ?? null /* model class */; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__trackedResource).Type; } + + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string UserDetailEmail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).UserDetailEmail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)Property).UserDetailEmail = value ?? null; } + + /// Creates an new instance. + public FileSystemResource() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Azure-AsyncOperation", out var __azureAsyncOperationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).AzureAsyncOperation = System.Linq.Enumerable.FirstOrDefault(__azureAsyncOperationHeader0) is string __headerAzureAsyncOperationHeader0 ? __headerAzureAsyncOperationHeader0 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader1) is string __headerRetryAfterHeader1 ? int.TryParse( __headerRetryAfterHeader1, out int __headerRetryAfterHeader1Value ) ? __headerRetryAfterHeader1Value : default(int?) : default(int?); + } + } + + /// Validates that this object meets the validation criteria. + /// an instance that will receive validation + /// events. + /// + /// A that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__trackedResource), __trackedResource); + await eventListener.AssertObjectIsValid(nameof(__trackedResource), __trackedResource); + } + } + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + public partial interface IFileSystemResource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource + { + /// Initial administrator password of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + string AdminPassword { get; set; } + /// Availability zone + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + string AvailabilityZone { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Azure-AsyncOperation", + PossibleTypes = new [] { typeof(string) })] + string AzureAsyncOperation { get; set; } + /// File system Id of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + string ClusterLoginUrl { get; set; } + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + string DelegatedSubnetId { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"marketplaceSubscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; } + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailTermUnit { get; set; } + /// Private IPs of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List PrivateIP { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted")] + string ProvisioningState { get; } + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + /// Storage Sku + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + string StorageSku { get; set; } + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmail { get; set; } + + } + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + internal partial interface IFileSystemResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal + { + /// Initial administrator password of the resource + string AdminPassword { get; set; } + /// Availability zone + string AvailabilityZone { get; set; } + + string AzureAsyncOperation { get; set; } + /// File system Id of the resource + string ClusterLoginUrl { get; set; } + /// Delegated subnet id for Vnet injection + string DelegatedSubnetId { get; set; } + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Identity { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityPrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityTenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Marketplace Subscription Id + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; set; } + /// Offer Id + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + string MarketplaceDetailTermUnit { get; set; } + /// Private IPs of the resource + System.Collections.Generic.List PrivateIP { get; set; } + /// The resource-specific properties for this resource. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties Property { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted")] + string ProvisioningState { get; set; } + + int? RetryAfter { get; set; } + /// Storage Sku + string StorageSku { get; set; } + /// User Details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get; set; } + /// User Email + string UserDetailEmail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.json.cs new file mode 100644 index 00000000000..2f8f0b7c947 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResource.json.cs @@ -0,0 +1,112 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + public partial class FileSystemResource + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemResource(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __trackedResource = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TrackedResource(json); + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceProperties.FromJson(__jsonProperties) : _property;} + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemResource(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.PowerShell.cs new file mode 100644 index 00000000000..6fce440584b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The response of a FileSystemResource list operation. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceListResultTypeConverter))] + public partial class FileSystemResourceListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemResourceListResult(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.Qumulo.Models.IFileSystemResourceListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemResourceListResult(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemResourceListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FileSystemResourceListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal)this).NextLink, 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.Qumulo.Models.IFileSystemResourceListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The response of a FileSystemResource list operation. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceListResultTypeConverter))] + public partial interface IFileSystemResourceListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.TypeConverter.cs new file mode 100644 index 00000000000..6e26e5b9f3f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemResourceListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemResourceListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemResourceListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemResourceListResult.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.cs new file mode 100644 index 00000000000..e910666ef0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The response of a FileSystemResource list operation. + public partial class FileSystemResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The FileSystemResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public FileSystemResourceListResult() + { + + } + } + /// The response of a FileSystemResource list operation. + public partial interface IFileSystemResourceListResult : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The FileSystemResource items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The FileSystemResource items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource) })] + System.Collections.Generic.List Value { get; set; } + + } + /// The response of a FileSystemResource list operation. + internal partial interface IFileSystemResourceListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The FileSystemResource items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.json.cs new file mode 100644 index 00000000000..4e933920bc2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceListResult.json.cs @@ -0,0 +1,116 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The response of a FileSystemResource list operation. + public partial class FileSystemResourceListResult + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemResourceListResult(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource) (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemResourceListResult(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.PowerShell.cs new file mode 100644 index 00000000000..00487e2ba2d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.PowerShell.cs @@ -0,0 +1,282 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Properties specific to the Qumulo File System resource + [System.ComponentModel.TypeConverter(typeof(FileSystemResourcePropertiesTypeConverter))] + public partial class FileSystemResourceProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemResourceProperties(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.Qumulo.Models.IFileSystemResourceProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemResourceProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemResourceProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StorageSku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).StorageSku = (string) content.GetValueForProperty("StorageSku",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).StorageSku, global::System.Convert.ToString); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ClusterLoginUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ClusterLoginUrl = (string) content.GetValueForProperty("ClusterLoginUrl",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ClusterLoginUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).PrivateIP = (System.Collections.Generic.List) content.GetValueForProperty("PrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).PrivateIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AdminPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AdminPassword = (string) content.GetValueForProperty("AdminPassword",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AdminPassword, global::System.Convert.ToString); + } + if (content.Contains("AvailabilityZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AvailabilityZone = (string) content.GetValueForProperty("AvailabilityZone",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AvailabilityZone, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetailEmail, 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 FileSystemResourceProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("ProvisioningState")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ProvisioningState = (string) content.GetValueForProperty("ProvisioningState",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ProvisioningState, global::System.Convert.ToString); + } + if (content.Contains("StorageSku")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).StorageSku = (string) content.GetValueForProperty("StorageSku",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).StorageSku, global::System.Convert.ToString); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("ClusterLoginUrl")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ClusterLoginUrl = (string) content.GetValueForProperty("ClusterLoginUrl",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).ClusterLoginUrl, global::System.Convert.ToString); + } + if (content.Contains("PrivateIP")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).PrivateIP = (System.Collections.Generic.List) content.GetValueForProperty("PrivateIP",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).PrivateIP, __y => TypeConverterExtensions.SelectToList(__y, global::System.Convert.ToString)); + } + if (content.Contains("AdminPassword")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AdminPassword = (string) content.GetValueForProperty("AdminPassword",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AdminPassword, global::System.Convert.ToString); + } + if (content.Contains("AvailabilityZone")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AvailabilityZone = (string) content.GetValueForProperty("AvailabilityZone",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).AvailabilityZone, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal)this).UserDetailEmail, 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.Qumulo.Models.IFileSystemResourceProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Properties specific to the Qumulo File System resource + [System.ComponentModel.TypeConverter(typeof(FileSystemResourcePropertiesTypeConverter))] + public partial interface IFileSystemResourceProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.TypeConverter.cs new file mode 100644 index 00000000000..b6d0568d9bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemResourcePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemResourceProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemResourceProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemResourceProperties.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.cs new file mode 100644 index 00000000000..76000be3bc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.cs @@ -0,0 +1,325 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Properties specific to the Qumulo File System resource + public partial class FileSystemResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal + { + + /// Backing field for property. + private string _adminPassword; + + /// Initial administrator password of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string AdminPassword { get => this._adminPassword; set => this._adminPassword = value; } + + /// Backing field for property. + private string _availabilityZone; + + /// Availability zone + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string AvailabilityZone { get => this._availabilityZone; set => this._availabilityZone = value; } + + /// Backing field for property. + private string _clusterLoginUrl; + + /// File system Id of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string ClusterLoginUrl { get => this._clusterLoginUrl; set => this._clusterLoginUrl = value; } + + /// Backing field for property. + private string _delegatedSubnetId; + + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string DelegatedSubnetId { get => this._delegatedSubnetId; set => this._delegatedSubnetId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails _marketplaceDetail; + + /// Marketplace details + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails()); set => this._marketplaceDetail = value; } + + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus; } + + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferId = value ; } + + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PlanId = value ; } + + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PublisherId = value ?? null; } + + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).TermUnit = value ?? null; } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal.MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails()); set { {_marketplaceDetail = value;} } } + + /// Internal Acessors for MarketplaceDetailMarketplaceSubscriptionStatus + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal.MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus = value; } + + /// Internal Acessors for ProvisioningState + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal.ProvisioningState { get => this._provisioningState; set { {_provisioningState = value;} } } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourcePropertiesInternal.UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails()); set { {_userDetail = value;} } } + + /// Backing field for property. + private System.Collections.Generic.List _privateIP; + + /// Private IPs of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public System.Collections.Generic.List PrivateIP { get => this._privateIP; set => this._privateIP = value; } + + /// Backing field for property. + private string _provisioningState; + + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string ProvisioningState { get => this._provisioningState; } + + /// Backing field for property. + private string _storageSku; + + /// Storage Sku + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string StorageSku { get => this._storageSku; set => this._storageSku = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails _userDetail; + + /// User Details + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails()); set => this._userDetail = value; } + + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string UserDetailEmail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)UserDetail).Email; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)UserDetail).Email = value ; } + + /// Creates an new instance. + public FileSystemResourceProperties() + { + + } + } + /// Properties specific to the Qumulo File System resource + public partial interface IFileSystemResourceProperties : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// Initial administrator password of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + string AdminPassword { get; set; } + /// Availability zone + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + string AvailabilityZone { get; set; } + /// File system Id of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + string ClusterLoginUrl { get; set; } + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + string DelegatedSubnetId { get; set; } + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"marketplaceSubscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; } + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailTermUnit { get; set; } + /// Private IPs of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + System.Collections.Generic.List PrivateIP { get; set; } + /// Provisioning State of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Provisioning State of the resource", + SerializedName = @"provisioningState", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted")] + string ProvisioningState { get; } + /// Storage Sku + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + string StorageSku { get; set; } + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmail { get; set; } + + } + /// Properties specific to the Qumulo File System resource + internal partial interface IFileSystemResourcePropertiesInternal + + { + /// Initial administrator password of the resource + string AdminPassword { get; set; } + /// Availability zone + string AvailabilityZone { get; set; } + /// File system Id of the resource + string ClusterLoginUrl { get; set; } + /// Delegated subnet id for Vnet injection + string DelegatedSubnetId { get; set; } + /// Marketplace details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Marketplace Subscription Id + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; set; } + /// Offer Id + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + string MarketplaceDetailTermUnit { get; set; } + /// Private IPs of the resource + System.Collections.Generic.List PrivateIP { get; set; } + /// Provisioning State of the resource + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Accepted", "Creating", "Updating", "Deleting", "Succeeded", "Failed", "Canceled", "Deleted")] + string ProvisioningState { get; set; } + /// Storage Sku + string StorageSku { get; set; } + /// User Details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get; set; } + /// User Email + string UserDetailEmail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.json.cs new file mode 100644 index 00000000000..eb6b99a6a50 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceProperties.json.cs @@ -0,0 +1,133 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Properties specific to the Qumulo File System resource + public partial class FileSystemResourceProperties + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemResourceProperties(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplaceDetail = If( json?.PropertyT("marketplaceDetails"), out var __jsonMarketplaceDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails.FromJson(__jsonMarketplaceDetails) : _marketplaceDetail;} + {_userDetail = If( json?.PropertyT("userDetails"), out var __jsonUserDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails.FromJson(__jsonUserDetails) : _userDetail;} + {_provisioningState = If( json?.PropertyT("provisioningState"), out var __jsonProvisioningState) ? (string)__jsonProvisioningState : (string)_provisioningState;} + {_storageSku = If( json?.PropertyT("storageSku"), out var __jsonStorageSku) ? (string)__jsonStorageSku : (string)_storageSku;} + {_delegatedSubnetId = If( json?.PropertyT("delegatedSubnetId"), out var __jsonDelegatedSubnetId) ? (string)__jsonDelegatedSubnetId : (string)_delegatedSubnetId;} + {_clusterLoginUrl = If( json?.PropertyT("clusterLoginUrl"), out var __jsonClusterLoginUrl) ? (string)__jsonClusterLoginUrl : (string)_clusterLoginUrl;} + {_privateIP = If( json?.PropertyT("privateIPs"), out var __jsonPrivateIPs) ? If( __jsonPrivateIPs as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(string) (__u is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString __t ? (string)(__t.ToString()) : null)) ))() : null : _privateIP;} + {_adminPassword = If( json?.PropertyT("adminPassword"), out var __jsonAdminPassword) ? (string)__jsonAdminPassword : (string)_adminPassword;} + {_availabilityZone = If( json?.PropertyT("availabilityZone"), out var __jsonAvailabilityZone) ? (string)__jsonAvailabilityZone : (string)_availabilityZone;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemResourceProperties(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._marketplaceDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._marketplaceDetail.ToJson(null,serializationMode) : null, "marketplaceDetails" ,container.Add ); + AddIf( null != this._userDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._userDetail.ToJson(null,serializationMode) : null, "userDetails" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provisioningState)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._provisioningState.ToString()) : null, "provisioningState" ,container.Add ); + } + AddIf( null != (((object)this._storageSku)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._storageSku.ToString()) : null, "storageSku" ,container.Add ); + AddIf( null != (((object)this._delegatedSubnetId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._delegatedSubnetId.ToString()) : null, "delegatedSubnetId" ,container.Add ); + AddIf( null != (((object)this._clusterLoginUrl)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._clusterLoginUrl.ToString()) : null, "clusterLoginUrl" ,container.Add ); + if (null != this._privateIP) + { + var __w = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.XNodeArray(); + foreach( var __x in this._privateIP ) + { + AddIf(null != (((object)__x)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(__x.ToString()) : null ,__w.Add); + } + container.Add("privateIPs",__w); + } + AddIf( null != (((object)this._adminPassword)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._adminPassword.ToString()) : null, "adminPassword" ,container.Add ); + AddIf( null != (((object)this._availabilityZone)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._availabilityZone.ToString()) : null, "availabilityZone" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.PowerShell.cs new file mode 100644 index 00000000000..0a6600266ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.PowerShell.cs @@ -0,0 +1,290 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The type used for update operations of the FileSystemResource. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceUpdateTypeConverter))] + public partial class FileSystemResourceUpdate + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemResourceUpdate(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.Qumulo.Models.IFileSystemResourceUpdate DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemResourceUpdate(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemResourceUpdate(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetailEmail, 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 FileSystemResourceUpdate(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Identity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Identity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity) content.GetValueForProperty("Identity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Identity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentityTypeConverter.ConvertFrom); + } + if (content.Contains("Property")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Property = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties) content.GetValueForProperty("Property",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Property, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceUpdatePropertiesTypeConverter.ConvertFrom); + } + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("IdentityPrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityPrincipalId = (string) content.GetValueForProperty("IdentityPrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityPrincipalId, global::System.Convert.ToString); + } + if (content.Contains("IdentityTenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityTenantId = (string) content.GetValueForProperty("IdentityTenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityTenantId, global::System.Convert.ToString); + } + if (content.Contains("IdentityType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityType = (string) content.GetValueForProperty("IdentityType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityType, global::System.Convert.ToString); + } + if (content.Contains("IdentityUserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityUserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("IdentityUserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).IdentityUserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal)this).UserDetailEmail, 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.Qumulo.Models.IFileSystemResourceUpdate FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The type used for update operations of the FileSystemResource. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceUpdateTypeConverter))] + public partial interface IFileSystemResourceUpdate + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.TypeConverter.cs new file mode 100644 index 00000000000..12cc7bda8f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemResourceUpdateTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemResourceUpdate.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemResourceUpdate.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemResourceUpdate.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.cs new file mode 100644 index 00000000000..54fa5121088 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.cs @@ -0,0 +1,315 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The type used for update operations of the FileSystemResource. + public partial class FileSystemResourceUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal + { + + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DelegatedSubnetId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).DelegatedSubnetId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).DelegatedSubnetId = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity _identity; + + /// The managed service identities assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity()); set => this._identity = value; } + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; } + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId; } + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string IdentityType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).Type = value ?? null; } + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).UserAssignedIdentity = value ?? null /* model class */; } + + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus; } + + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailOfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailOfferId = value ?? null; } + + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailPlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailPlanId = value ?? null; } + + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailPublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailPublisherId = value ?? null; } + + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailTermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailTermUnit = value ?? null; } + + /// Internal Acessors for Identity + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.Identity { get => (this._identity = this._identity ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity()); set { {_identity = value;} } } + + /// Internal Acessors for IdentityPrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.IdentityPrincipalId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).PrincipalId = value; } + + /// Internal Acessors for IdentityTenantId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.IdentityTenantId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)Identity).TenantId = value; } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.MarketplaceDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetail = value; } + + /// Internal Acessors for MarketplaceDetailMarketplaceSubscriptionStatus + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).MarketplaceDetailMarketplaceSubscriptionStatus = value; } + + /// Internal Acessors for Property + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceUpdateProperties()); set { {_property = value;} } } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateInternal.UserDetail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).UserDetail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).UserDetail = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties _property; + + /// The updatable properties of the FileSystemResource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceUpdateProperties()); set => this._property = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Tags()); set => this._tag = value; } + + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string UserDetailEmail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).UserDetailEmail; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)Property).UserDetailEmail = value ?? null; } + + /// Creates an new instance. + public FileSystemResourceUpdate() + { + + } + } + /// The type used for update operations of the FileSystemResource. + public partial interface IFileSystemResourceUpdate : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + string DelegatedSubnetId { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string IdentityPrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string IdentityTenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"marketplaceSubscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; } + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailTermUnit { get; set; } + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get; set; } + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmail { get; set; } + + } + /// The type used for update operations of the FileSystemResource. + internal partial interface IFileSystemResourceUpdateInternal + + { + /// Delegated subnet id for Vnet injection + string DelegatedSubnetId { get; set; } + /// The managed service identities assigned to this resource. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity Identity { get; set; } + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityPrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string IdentityTenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string IdentityType { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities IdentityUserAssignedIdentity { get; set; } + /// Marketplace details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Marketplace Subscription Id + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; set; } + /// Offer Id + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + string MarketplaceDetailTermUnit { get; set; } + /// The updatable properties of the FileSystemResource. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties Property { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get; set; } + /// User Details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get; set; } + /// User Email + string UserDetailEmail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.json.cs new file mode 100644 index 00000000000..425ee273897 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdate.json.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The type used for update operations of the FileSystemResource. + public partial class FileSystemResourceUpdate + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemResourceUpdate(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_identity = If( json?.PropertyT("identity"), out var __jsonIdentity) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ManagedServiceIdentity.FromJson(__jsonIdentity) : _identity;} + {_property = If( json?.PropertyT("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceUpdateProperties.FromJson(__jsonProperties) : _property;} + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Tags.FromJson(__jsonTags) : _tag;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemResourceUpdate(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._identity ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._identity.ToJson(null,serializationMode) : null, "identity" ,container.Add ); + AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.PowerShell.cs new file mode 100644 index 00000000000..5d088d038f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The updatable properties of the FileSystemResource. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceUpdatePropertiesTypeConverter))] + public partial class FileSystemResourceUpdateProperties + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemResourceUpdateProperties(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.Qumulo.Models.IFileSystemResourceUpdateProperties DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemResourceUpdateProperties(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemResourceUpdateProperties(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetailEmail, 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 FileSystemResourceUpdateProperties(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails) content.GetValueForProperty("MarketplaceDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("UserDetail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetail = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails) content.GetValueForProperty("UserDetail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetail, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetailsTypeConverter.ConvertFrom); + } + if (content.Contains("DelegatedSubnetId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).DelegatedSubnetId = (string) content.GetValueForProperty("DelegatedSubnetId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).DelegatedSubnetId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPlanId = (string) content.GetValueForProperty("MarketplaceDetailPlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPlanId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailOfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailOfferId = (string) content.GetValueForProperty("MarketplaceDetailOfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailOfferId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailPublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPublisherId = (string) content.GetValueForProperty("MarketplaceDetailPublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailPublisherId, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailTermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailTermUnit = (string) content.GetValueForProperty("MarketplaceDetailTermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailTermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceDetailMarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceDetailMarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).MarketplaceDetailMarketplaceSubscriptionStatus, global::System.Convert.ToString); + } + if (content.Contains("UserDetailEmail")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetailEmail = (string) content.GetValueForProperty("UserDetailEmail",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal)this).UserDetailEmail, 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.Qumulo.Models.IFileSystemResourceUpdateProperties FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// The updatable properties of the FileSystemResource. + [System.ComponentModel.TypeConverter(typeof(FileSystemResourceUpdatePropertiesTypeConverter))] + public partial interface IFileSystemResourceUpdateProperties + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.TypeConverter.cs new file mode 100644 index 00000000000..b1e9c9e2b94 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.TypeConverter.cs @@ -0,0 +1,147 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemResourceUpdatePropertiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemResourceUpdateProperties.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemResourceUpdateProperties.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemResourceUpdateProperties.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.cs new file mode 100644 index 00000000000..85408a046e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.cs @@ -0,0 +1,200 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The updatable properties of the FileSystemResource. + public partial class FileSystemResourceUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal + { + + /// Backing field for property. + private string _delegatedSubnetId; + + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string DelegatedSubnetId { get => this._delegatedSubnetId; set => this._delegatedSubnetId = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails _marketplaceDetail; + + /// Marketplace details + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails()); set => this._marketplaceDetail = value; } + + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionId = value ?? null; } + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus; } + + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailOfferId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).OfferId = value ?? null; } + + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPlanId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PlanId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PlanId = value ?? null; } + + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailPublisherId { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PublisherId; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).PublisherId = value ?? null; } + + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string MarketplaceDetailTermUnit { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).TermUnit; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).TermUnit = value ?? null; } + + /// Internal Acessors for MarketplaceDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal.MarketplaceDetail { get => (this._marketplaceDetail = this._marketplaceDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails()); set { {_marketplaceDetail = value;} } } + + /// Internal Acessors for MarketplaceDetailMarketplaceSubscriptionStatus + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal.MarketplaceDetailMarketplaceSubscriptionStatus { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)MarketplaceDetail).MarketplaceSubscriptionStatus = value; } + + /// Internal Acessors for UserDetail + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdatePropertiesInternal.UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails()); set { {_userDetail = value;} } } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails _userDetail; + + /// User Details + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get => (this._userDetail = this._userDetail ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails()); set => this._userDetail = value; } + + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string UserDetailEmail { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)UserDetail).Email; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)UserDetail).Email = value ?? null; } + + /// Creates an new instance. + public FileSystemResourceUpdateProperties() + { + + } + } + /// The updatable properties of the FileSystemResource. + public partial interface IFileSystemResourceUpdateProperties : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// Delegated subnet id for Vnet injection + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + string DelegatedSubnetId { get; set; } + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"marketplaceSubscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; } + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceDetailTermUnit { get; set; } + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + string UserDetailEmail { get; set; } + + } + /// The updatable properties of the FileSystemResource. + internal partial interface IFileSystemResourceUpdatePropertiesInternal + + { + /// Delegated subnet id for Vnet injection + string DelegatedSubnetId { get; set; } + /// Marketplace details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails MarketplaceDetail { get; set; } + /// Marketplace Subscription Id + string MarketplaceDetailMarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceDetailMarketplaceSubscriptionStatus { get; set; } + /// Offer Id + string MarketplaceDetailOfferId { get; set; } + /// Plan Id + string MarketplaceDetailPlanId { get; set; } + /// Publisher Id + string MarketplaceDetailPublisherId { get; set; } + /// Term Unit + string MarketplaceDetailTermUnit { get; set; } + /// User Details + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails UserDetail { get; set; } + /// User Email + string UserDetailEmail { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.json.cs new file mode 100644 index 00000000000..867d043d158 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemResourceUpdateProperties.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The updatable properties of the FileSystemResource. + public partial class FileSystemResourceUpdateProperties + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemResourceUpdateProperties(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplaceDetail = If( json?.PropertyT("marketplaceDetails"), out var __jsonMarketplaceDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.MarketplaceDetails.FromJson(__jsonMarketplaceDetails) : _marketplaceDetail;} + {_userDetail = If( json?.PropertyT("userDetails"), out var __jsonUserDetails) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserDetails.FromJson(__jsonUserDetails) : _userDetail;} + {_delegatedSubnetId = If( json?.PropertyT("delegatedSubnetId"), out var __jsonDelegatedSubnetId) ? (string)__jsonDelegatedSubnetId : (string)_delegatedSubnetId;} + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdateProperties FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemResourceUpdateProperties(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != this._marketplaceDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._marketplaceDetail.ToJson(null,serializationMode) : null, "marketplaceDetails" ,container.Add ); + AddIf( null != this._userDetail ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._userDetail.ToJson(null,serializationMode) : null, "userDetails" ,container.Add ); + AddIf( null != (((object)this._delegatedSubnetId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._delegatedSubnetId.ToString()) : null, "delegatedSubnetId" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.PowerShell.cs new file mode 100644 index 00000000000..ae396863e1a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.PowerShell.cs @@ -0,0 +1,181 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(FileSystemsDeleteAcceptedResponseHeadersTypeConverter))] + public partial class FileSystemsDeleteAcceptedResponseHeaders + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new FileSystemsDeleteAcceptedResponseHeaders(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.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new FileSystemsDeleteAcceptedResponseHeaders(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal FileSystemsDeleteAcceptedResponseHeaders(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal FileSystemsDeleteAcceptedResponseHeaders(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("AzureAsyncOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).AzureAsyncOperation = (string) content.GetValueForProperty("AzureAsyncOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).AzureAsyncOperation, global::System.Convert.ToString); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("RetryAfter")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = (int?) content.GetValueForProperty("RetryAfter",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).RetryAfter, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int))); + } + 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.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(FileSystemsDeleteAcceptedResponseHeadersTypeConverter))] + public partial interface IFileSystemsDeleteAcceptedResponseHeaders + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.TypeConverter.cs new file mode 100644 index 00000000000..188efe0742e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.TypeConverter.cs @@ -0,0 +1,149 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class FileSystemsDeleteAcceptedResponseHeadersTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise + /// false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return FileSystemsDeleteAcceptedResponseHeaders.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return FileSystemsDeleteAcceptedResponseHeaders.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return FileSystemsDeleteAcceptedResponseHeaders.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.cs new file mode 100644 index 00000000000..b30f904944a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class FileSystemsDeleteAcceptedResponseHeaders : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IHeaderSerializable + { + + /// Backing field for property. + private string _azureAsyncOperation; + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string AzureAsyncOperation { get => this._azureAsyncOperation; set => this._azureAsyncOperation = value; } + + /// Backing field for property. + private string _location; + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Backing field for property. + private int? _retryAfter; + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public int? RetryAfter { get => this._retryAfter; set => this._retryAfter = value; } + + /// + /// Creates an new instance. + /// + public FileSystemsDeleteAcceptedResponseHeaders() + { + + } + + /// + void Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IHeaderSerializable.ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers) + { + if (headers.TryGetValues("Azure-AsyncOperation", out var __azureAsyncOperationHeader0)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).AzureAsyncOperation = System.Linq.Enumerable.FirstOrDefault(__azureAsyncOperationHeader0) is string __headerAzureAsyncOperationHeader0 ? __headerAzureAsyncOperationHeader0 : (string)null; + } + if (headers.TryGetValues("Location", out var __locationHeader1)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).Location = System.Linq.Enumerable.FirstOrDefault(__locationHeader1) is string __headerLocationHeader1 ? __headerLocationHeader1 : (string)null; + } + if (headers.TryGetValues("Retry-After", out var __retryAfterHeader2)) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeadersInternal)this).RetryAfter = System.Linq.Enumerable.FirstOrDefault(__retryAfterHeader2) is string __headerRetryAfterHeader2 ? int.TryParse( __headerRetryAfterHeader2, out int __headerRetryAfterHeader2Value ) ? __headerRetryAfterHeader2Value : default(int?) : default(int?); + } + } + } + public partial interface IFileSystemsDeleteAcceptedResponseHeaders + + { + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Azure-AsyncOperation", + PossibleTypes = new [] { typeof(string) })] + string AzureAsyncOperation { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Location", + PossibleTypes = new [] { typeof(string) })] + string Location { get; set; } + + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"", + SerializedName = @"Retry-After", + PossibleTypes = new [] { typeof(int) })] + int? RetryAfter { get; set; } + + } + internal partial interface IFileSystemsDeleteAcceptedResponseHeadersInternal + + { + string AzureAsyncOperation { get; set; } + + string Location { get; set; } + + int? RetryAfter { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.json.cs new file mode 100644 index 00000000000..30017c192bb --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/FileSystemsDeleteAcceptedResponseHeaders.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class FileSystemsDeleteAcceptedResponseHeaders + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal FileSystemsDeleteAcceptedResponseHeaders(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + AfterFromJson(json); + } + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemsDeleteAcceptedResponseHeaders FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new FileSystemsDeleteAcceptedResponseHeaders(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs new file mode 100644 index 00000000000..d28e6a810cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Managed service identity (system assigned and/or user assigned identities) + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityTypeConverter))] + public partial class ManagedServiceIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new ManagedServiceIdentity(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.Qumulo.Models.IManagedServiceIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new ManagedServiceIdentity(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.Qumulo.Models.IManagedServiceIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal ManagedServiceIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.ConvertFrom); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal ManagedServiceIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("TenantId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).TenantId = (string) content.GetValueForProperty("TenantId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).TenantId, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("UserAssignedIdentity")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) content.GetValueForProperty("UserAssignedIdentity",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal)this).UserAssignedIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentitiesTypeConverter.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Managed service identity (system assigned and/or user assigned identities) + [System.ComponentModel.TypeConverter(typeof(ManagedServiceIdentityTypeConverter))] + public partial interface IManagedServiceIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs new file mode 100644 index 00000000000..810c0e4252d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ManagedServiceIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return ManagedServiceIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return ManagedServiceIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return ManagedServiceIdentity.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.cs new file mode 100644 index 00000000000..8da940a4bb0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.cs @@ -0,0 +1,132 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal + { + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Internal Acessors for TenantId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentityInternal.TenantId { get => this._tenantId; set { {_tenantId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Backing field for property. + private string _tenantId; + + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string TenantId { get => this._tenantId; } + + /// Backing field for property. + private string _type; + + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Type { get => this._type; set => this._type = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities _userAssignedIdentity; + + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities UserAssignedIdentity { get => (this._userAssignedIdentity = this._userAssignedIdentity ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentities()); set => this._userAssignedIdentity = value; } + + /// Creates an new instance. + public ManagedServiceIdentity() + { + + } + } + /// Managed service identity (system assigned and/or user assigned identities) + public partial interface IManagedServiceIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.", + SerializedName = @"tenantId", + PossibleTypes = new [] { typeof(string) })] + string TenantId { get; } + /// The type of managed identity assigned to this resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of managed identity assigned to this resource.", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identities assigned to this resource by the user.", + SerializedName = @"userAssignedIdentities", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities UserAssignedIdentity { get; set; } + + } + /// Managed service identity (system assigned and/or user assigned identities) + internal partial interface IManagedServiceIdentityInternal + + { + /// + /// The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string PrincipalId { get; set; } + /// + /// The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity. + /// + string TenantId { get; set; } + /// The type of managed identity assigned to this resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("None", "SystemAssigned", "UserAssigned", "SystemAssigned,UserAssigned")] + string Type { get; set; } + /// The identities assigned to this resource by the user. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities UserAssignedIdentity { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.json.cs new file mode 100644 index 00000000000..f8625a9fc9c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/ManagedServiceIdentity.json.cs @@ -0,0 +1,118 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Managed service identity (system assigned and/or user assigned identities) + public partial class ManagedServiceIdentity + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IManagedServiceIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new ManagedServiceIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal ManagedServiceIdentity(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)_principalId;} + {_tenantId = If( json?.PropertyT("tenantId"), out var __jsonTenantId) ? (string)__jsonTenantId : (string)_tenantId;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + {_userAssignedIdentity = If( json?.PropertyT("userAssignedIdentities"), out var __jsonUserAssignedIdentities) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentities.FromJson(__jsonUserAssignedIdentities) : _userAssignedIdentity;} + 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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._tenantId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._tenantId.ToString()) : null, "tenantId" ,container.Add ); + } + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + AddIf( null != this._userAssignedIdentity ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._userAssignedIdentity.ToJson(null,serializationMode) : null, "userAssignedIdentities" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs new file mode 100644 index 00000000000..74e61a61fdf --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// MarketplaceDetails of Qumulo FileSystem resource + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial class MarketplaceDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new MarketplaceDetails(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.Qumulo.Models.IMarketplaceDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new MarketplaceDetails(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.Qumulo.Models.IMarketplaceDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal MarketplaceDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionStatus, 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 MarketplaceDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("MarketplaceSubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionId = (string) content.GetValueForProperty("MarketplaceSubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("PlanId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PlanId = (string) content.GetValueForProperty("PlanId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PlanId, global::System.Convert.ToString); + } + if (content.Contains("OfferId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).OfferId = (string) content.GetValueForProperty("OfferId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).OfferId, global::System.Convert.ToString); + } + if (content.Contains("PublisherId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PublisherId = (string) content.GetValueForProperty("PublisherId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).PublisherId, global::System.Convert.ToString); + } + if (content.Contains("TermUnit")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).TermUnit = (string) content.GetValueForProperty("TermUnit",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).TermUnit, global::System.Convert.ToString); + } + if (content.Contains("MarketplaceSubscriptionStatus")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionStatus = (string) content.GetValueForProperty("MarketplaceSubscriptionStatus",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal)this).MarketplaceSubscriptionStatus, 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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// MarketplaceDetails of Qumulo FileSystem resource + [System.ComponentModel.TypeConverter(typeof(MarketplaceDetailsTypeConverter))] + public partial interface IMarketplaceDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs new file mode 100644 index 00000000000..55ebe0a6ca5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class MarketplaceDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return MarketplaceDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return MarketplaceDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return MarketplaceDetails.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.cs new file mode 100644 index 00000000000..47dc5162f30 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// MarketplaceDetails of Qumulo FileSystem resource + public partial class MarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal + { + + /// Backing field for property. + private string _marketplaceSubscriptionId; + + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string MarketplaceSubscriptionId { get => this._marketplaceSubscriptionId; set => this._marketplaceSubscriptionId = value; } + + /// Backing field for property. + private string _marketplaceSubscriptionStatus; + + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string MarketplaceSubscriptionStatus { get => this._marketplaceSubscriptionStatus; } + + /// Internal Acessors for MarketplaceSubscriptionStatus + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetailsInternal.MarketplaceSubscriptionStatus { get => this._marketplaceSubscriptionStatus; set { {_marketplaceSubscriptionStatus = value;} } } + + /// Backing field for property. + private string _offerId; + + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string OfferId { get => this._offerId; set => this._offerId = value; } + + /// Backing field for property. + private string _planId; + + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string PlanId { get => this._planId; set => this._planId = value; } + + /// Backing field for property. + private string _publisherId; + + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string PublisherId { get => this._publisherId; set => this._publisherId = value; } + + /// Backing field for property. + private string _termUnit; + + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string TermUnit { get => this._termUnit; set => this._termUnit = value; } + + /// Creates an new instance. + public MarketplaceDetails() + { + + } + } + /// MarketplaceDetails of Qumulo FileSystem resource + public partial interface IMarketplaceDetails : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// Marketplace Subscription Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Marketplace subscription status", + SerializedName = @"marketplaceSubscriptionStatus", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; } + /// Offer Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + string OfferId { get; set; } + /// Plan Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + string PlanId { get; set; } + /// Publisher Id + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + string PublisherId { get; set; } + /// Term Unit + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + string TermUnit { get; set; } + + } + /// MarketplaceDetails of Qumulo FileSystem resource + internal partial interface IMarketplaceDetailsInternal + + { + /// Marketplace Subscription Id + string MarketplaceSubscriptionId { get; set; } + /// Marketplace subscription status + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("PendingFulfillmentStart", "Subscribed", "Suspended", "Unsubscribed")] + string MarketplaceSubscriptionStatus { get; set; } + /// Offer Id + string OfferId { get; set; } + /// Plan Id + string PlanId { get; set; } + /// Publisher Id + string PublisherId { get; set; } + /// Term Unit + string TermUnit { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.json.cs new file mode 100644 index 00000000000..35c53a8717c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/MarketplaceDetails.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// MarketplaceDetails of Qumulo FileSystem resource + public partial class MarketplaceDetails + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IMarketplaceDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new MarketplaceDetails(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal MarketplaceDetails(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_marketplaceSubscriptionId = If( json?.PropertyT("marketplaceSubscriptionId"), out var __jsonMarketplaceSubscriptionId) ? (string)__jsonMarketplaceSubscriptionId : (string)_marketplaceSubscriptionId;} + {_planId = If( json?.PropertyT("planId"), out var __jsonPlanId) ? (string)__jsonPlanId : (string)_planId;} + {_offerId = If( json?.PropertyT("offerId"), out var __jsonOfferId) ? (string)__jsonOfferId : (string)_offerId;} + {_publisherId = If( json?.PropertyT("publisherId"), out var __jsonPublisherId) ? (string)__jsonPublisherId : (string)_publisherId;} + {_termUnit = If( json?.PropertyT("termUnit"), out var __jsonTermUnit) ? (string)__jsonTermUnit : (string)_termUnit;} + {_marketplaceSubscriptionStatus = If( json?.PropertyT("marketplaceSubscriptionStatus"), out var __jsonMarketplaceSubscriptionStatus) ? (string)__jsonMarketplaceSubscriptionStatus : (string)_marketplaceSubscriptionStatus;} + 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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._marketplaceSubscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._marketplaceSubscriptionId.ToString()) : null, "marketplaceSubscriptionId" ,container.Add ); + AddIf( null != (((object)this._planId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._planId.ToString()) : null, "planId" ,container.Add ); + AddIf( null != (((object)this._offerId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._offerId.ToString()) : null, "offerId" ,container.Add ); + AddIf( null != (((object)this._publisherId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._publisherId.ToString()) : null, "publisherId" ,container.Add ); + AddIf( null != (((object)this._termUnit)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._termUnit.ToString()) : null, "termUnit" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._marketplaceSubscriptionStatus)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._marketplaceSubscriptionStatus.ToString()) : null, "marketplaceSubscriptionStatus" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.PowerShell.cs new file mode 100644 index 00000000000..e4f89f30f25 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.PowerShell.cs @@ -0,0 +1,228 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial class Operation + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Operation(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Operation(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Operation(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Operation(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Display")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Display = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay) content.GetValueForProperty("Display",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Display, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationDisplayTypeConverter.ConvertFrom); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("IsDataAction")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).IsDataAction = (bool?) content.GetValueForProperty("IsDataAction",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).IsDataAction, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); + } + if (content.Contains("Origin")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Origin = (string) content.GetValueForProperty("Origin",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).Origin, global::System.Convert.ToString); + } + if (content.Contains("ActionType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).ActionType = (string) content.GetValueForProperty("ActionType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).ActionType, global::System.Convert.ToString); + } + if (content.Contains("DisplayProvider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayProvider = (string) content.GetValueForProperty("DisplayProvider",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayProvider, global::System.Convert.ToString); + } + if (content.Contains("DisplayResource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayResource = (string) content.GetValueForProperty("DisplayResource",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayResource, global::System.Convert.ToString); + } + if (content.Contains("DisplayOperation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayOperation = (string) content.GetValueForProperty("DisplayOperation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayOperation, global::System.Convert.ToString); + } + if (content.Contains("DisplayDescription")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayDescription = (string) content.GetValueForProperty("DisplayDescription",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal)this).DisplayDescription, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + [System.ComponentModel.TypeConverter(typeof(OperationTypeConverter))] + public partial interface IOperation + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.TypeConverter.cs new file mode 100644 index 00000000000..2d3132da9b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Operation.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Operation.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Operation.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.cs new file mode 100644 index 00000000000..1278a3218ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.cs @@ -0,0 +1,279 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal + { + + /// Backing field for property. + private string _actionType; + + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string ActionType { get => this._actionType; set => this._actionType = value; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay _display; + + /// Localized display information for this particular operation. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationDisplay()); } + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Description; } + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Operation; } + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Provider; } + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Resource; } + + /// Backing field for property. + private bool? _isDataAction; + + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public bool? IsDataAction { get => this._isDataAction; } + + /// Internal Acessors for Display + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.Display { get => (this._display = this._display ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationDisplay()); set { {_display = value;} } } + + /// Internal Acessors for DisplayDescription + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.DisplayDescription { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Description; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Description = value; } + + /// Internal Acessors for DisplayOperation + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.DisplayOperation { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Operation; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Operation = value; } + + /// Internal Acessors for DisplayProvider + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.DisplayProvider { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Provider; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Provider = value; } + + /// Internal Acessors for DisplayResource + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.DisplayResource { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Resource; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)Display).Resource = value; } + + /// Internal Acessors for IsDataAction + bool? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.IsDataAction { get => this._isDataAction; set { {_isDataAction = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for Origin + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationInternal.Origin { get => this._origin; set { {_origin = value;} } } + + /// Backing field for property. + private string _name; + + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private string _origin; + + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Origin { get => this._origin; } + + /// Creates an new instance. + public Operation() + { + + } + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + public partial interface IOperation : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Extensible enum. Indicates the action type. ""Internal"" refers to actions that are for internal only APIs.", + SerializedName = @"actionType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string DisplayDescription { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string DisplayOperation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string DisplayProvider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string DisplayResource { get; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"Whether the operation applies to data-plane. This is ""true"" for data-plane operations and ""false"" for Azure Resource Manager/control-plane operations.", + SerializedName = @"isDataAction", + PossibleTypes = new [] { typeof(bool) })] + bool? IsDataAction { get; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the operation, as per Resource-Based Access Control (RBAC). Examples: ""Microsoft.Compute/virtualMachines/write"", ""Microsoft.Compute/virtualMachines/capture/action""", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is ""user,system""", + SerializedName = @"origin", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; } + + } + /// Details of a REST API operation, returned from the Resource Provider Operations API + internal partial interface IOperationInternal + + { + /// + /// Extensible enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("Internal")] + string ActionType { get; set; } + /// Localized display information for this particular operation. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay Display { get; set; } + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string DisplayDescription { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string DisplayOperation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string DisplayProvider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string DisplayResource { get; set; } + /// + /// Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for Azure Resource Manager/control-plane + /// operations. + /// + bool? IsDataAction { get; set; } + /// + /// The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", + /// "Microsoft.Compute/virtualMachines/capture/action" + /// + string Name { get; set; } + /// + /// The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is + /// "user,system" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("user", "system", "user,system")] + string Origin { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.json.cs new file mode 100644 index 00000000000..acf353d6c5b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Operation.json.cs @@ -0,0 +1,126 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Details of a REST API operation, returned from the Resource Provider Operations API + /// + public partial class Operation + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new Operation(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal Operation(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Models.OperationDisplay.FromJson(__jsonDisplay) : _display;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_isDataAction = If( json?.PropertyT("isDataAction"), out var __jsonIsDataAction) ? (bool?)__jsonIsDataAction : _isDataAction;} + {_origin = If( json?.PropertyT("origin"), out var __jsonOrigin) ? (string)__jsonOrigin : (string)_origin;} + {_actionType = If( json?.PropertyT("actionType"), out var __jsonActionType) ? (string)__jsonActionType : (string)_actionType;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._display ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._display.ToJson(null,serializationMode) : null, "display" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._isDataAction ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonBoolean((bool)this._isDataAction) : null, "isDataAction" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._origin)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._origin.ToString()) : null, "origin" ,container.Add ); + } + AddIf( null != (((object)this._actionType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._actionType.ToString()) : null, "actionType" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs new file mode 100644 index 00000000000..403c021e944 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.PowerShell.cs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial class OperationDisplay + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationDisplay(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationDisplay(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationDisplay(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationDisplay(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Provider")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Provider = (string) content.GetValueForProperty("Provider",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Provider, global::System.Convert.ToString); + } + if (content.Contains("Resource")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Resource = (string) content.GetValueForProperty("Resource",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Resource, global::System.Convert.ToString); + } + if (content.Contains("Operation")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Operation = (string) content.GetValueForProperty("Operation",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Operation, global::System.Convert.ToString); + } + if (content.Contains("Description")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Description = (string) content.GetValueForProperty("Description",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal)this).Description, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Localized display information for and operation. + [System.ComponentModel.TypeConverter(typeof(OperationDisplayTypeConverter))] + public partial interface IOperationDisplay + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs new file mode 100644 index 00000000000..61f42262fb9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationDisplayTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationDisplay.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationDisplay.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.cs new file mode 100644 index 00000000000..3d0e60c5444 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.cs @@ -0,0 +1,151 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Localized display information for and operation. + public partial class OperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal + { + + /// Backing field for property. + private string _description; + + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Description { get => this._description; } + + /// Internal Acessors for Description + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal.Description { get => this._description; set { {_description = value;} } } + + /// Internal Acessors for Operation + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal.Operation { get => this._operation; set { {_operation = value;} } } + + /// Internal Acessors for Provider + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal.Provider { get => this._provider; set { {_provider = value;} } } + + /// Internal Acessors for Resource + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplayInternal.Resource { get => this._resource; set { {_resource = value;} } } + + /// Backing field for property. + private string _operation; + + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Operation { get => this._operation; } + + /// Backing field for property. + private string _provider; + + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Provider { get => this._provider; } + + /// Backing field for property. + private string _resource; + + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Resource { get => this._resource; } + + /// Creates an new instance. + public OperationDisplay() + { + + } + } + /// Localized display information for and operation. + public partial interface IOperationDisplay : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The short, localized friendly description of the operation; suitable for tool tips and detailed views.", + SerializedName = @"description", + PossibleTypes = new [] { typeof(string) })] + string Description { get; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The concise, localized friendly name for the operation; suitable for dropdowns. E.g. ""Create or Update Virtual Machine"", ""Restart Virtual Machine"".", + SerializedName = @"operation", + PossibleTypes = new [] { typeof(string) })] + string Operation { get; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly form of the resource provider name, e.g. ""Microsoft Monitoring Insights"" or ""Microsoft Compute"".", + SerializedName = @"provider", + PossibleTypes = new [] { typeof(string) })] + string Provider { get; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The localized friendly name of the resource type related to this operation. E.g. ""Virtual Machines"" or ""Job Schedule Collections"".", + SerializedName = @"resource", + PossibleTypes = new [] { typeof(string) })] + string Resource { get; } + + } + /// Localized display information for and operation. + internal partial interface IOperationDisplayInternal + + { + /// + /// The short, localized friendly description of the operation; suitable for tool tips and detailed views. + /// + string Description { get; set; } + /// + /// The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", + /// "Restart Virtual Machine". + /// + string Operation { get; set; } + /// + /// The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + /// + string Provider { get; set; } + /// + /// The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + /// + string Resource { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.json.cs new file mode 100644 index 00000000000..4ad7535526b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationDisplay.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Localized display information for and 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationDisplay FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new OperationDisplay(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal OperationDisplay(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_provider = If( json?.PropertyT("provider"), out var __jsonProvider) ? (string)__jsonProvider : (string)_provider;} + {_resource = If( json?.PropertyT("resource"), out var __jsonResource) ? (string)__jsonResource : (string)_resource;} + {_operation = If( json?.PropertyT("operation"), out var __jsonOperation) ? (string)__jsonOperation : (string)_operation;} + {_description = If( json?.PropertyT("description"), out var __jsonDescription) ? (string)__jsonDescription : (string)_description;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._provider)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._provider.ToString()) : null, "provider" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._resource)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._resource.ToString()) : null, "resource" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._operation)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._operation.ToString()) : null, "operation" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._description)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._description.ToString()) : null, "description" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.PowerShell.cs new file mode 100644 index 00000000000..ec4a28f37b4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial class OperationListResult + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new OperationListResult(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new OperationListResult(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal OperationListResult(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal OperationListResult(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Value")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).Value = (System.Collections.Generic.List) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).Value, __y => TypeConverterExtensions.SelectToList(__y, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationTypeConverter.ConvertFrom)); + } + if (content.Contains("NextLink")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal)this).NextLink, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + [System.ComponentModel.TypeConverter(typeof(OperationListResultTypeConverter))] + public partial interface IOperationListResult + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs new file mode 100644 index 00000000000..bab71bed16e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class OperationListResultTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return OperationListResult.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return OperationListResult.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.cs new file mode 100644 index 00000000000..86b6394fcb3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResultInternal + { + + /// Backing field for property. + private string _nextLink; + + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string NextLink { get => this._nextLink; set => this._nextLink = value; } + + /// Backing field for property. + private System.Collections.Generic.List _value; + + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public System.Collections.Generic.List Value { get => this._value; set => this._value = value; } + + /// Creates an new instance. + public OperationListResult() + { + + } + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + public partial interface IOperationListResult : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The link to the next page of items + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The link to the next page of items", + SerializedName = @"nextLink", + PossibleTypes = new [] { typeof(string) })] + string NextLink { get; set; } + /// The Operation items on this page + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The Operation items on this page", + SerializedName = @"value", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation) })] + System.Collections.Generic.List Value { get; set; } + + } + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + internal partial interface IOperationListResultInternal + + { + /// The link to the next page of items + string NextLink { get; set; } + /// The Operation items on this page + System.Collections.Generic.List Value { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.json.cs new file mode 100644 index 00000000000..1ebc428b1f9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/OperationListResult.json.cs @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of + /// results. + /// + public partial class OperationListResult + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new OperationListResult(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal OperationListResult(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonArray, out var __v) ? new global::System.Func>(()=> global::System.Linq.Enumerable.ToList(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation) (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Operation.FromJson(__u) )) ))() : null : _value;} + {_nextLink = If( json?.PropertyT("nextLink"), out var __jsonNextLink) ? (string)__jsonNextLink : (string)_nextLink;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.XNodeArray(); + foreach( var __x in this._value ) + { + AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); + } + container.Add("value",__w); + } + AddIf( null != (((object)this._nextLink)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._nextLink.ToString()) : null, "nextLink" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.PowerShell.cs new file mode 100644 index 00000000000..5dc277c45fd --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.PowerShell.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + [System.ComponentModel.TypeConverter(typeof(QumuloIdentityTypeConverter))] + public partial class QumuloIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new QumuloIdentity(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.Qumulo.Models.IQumuloIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new QumuloIdentity(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.Qumulo.Models.IQumuloIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal QumuloIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("FileSystemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).FileSystemName = (string) content.GetValueForProperty("FileSystemName",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).FileSystemName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)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 QumuloIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SubscriptionId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).SubscriptionId = (string) content.GetValueForProperty("SubscriptionId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).SubscriptionId, global::System.Convert.ToString); + } + if (content.Contains("ResourceGroupName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).ResourceGroupName = (string) content.GetValueForProperty("ResourceGroupName",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).ResourceGroupName, global::System.Convert.ToString); + } + if (content.Contains("FileSystemName")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).FileSystemName = (string) content.GetValueForProperty("FileSystemName",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).FileSystemName, global::System.Convert.ToString); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal)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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + [System.ComponentModel.TypeConverter(typeof(QumuloIdentityTypeConverter))] + public partial interface IQumuloIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.TypeConverter.cs new file mode 100644 index 00000000000..8582f73415c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.TypeConverter.cs @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class QumuloIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + // we allow string conversion too. + if (type == typeof(global::System.String)) + { + return true; + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity 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 QumuloIdentity { Id = sourceValue }; + } + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return QumuloIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return QumuloIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return QumuloIdentity.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.cs new file mode 100644 index 00000000000..c293a5257e8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class QumuloIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentityInternal + { + + /// Backing field for property. + private string _fileSystemName; + + /// Name of the File System resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string FileSystemName { get => this._fileSystemName; set => this._fileSystemName = value; } + + /// Backing field for property. + private string _id; + + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Creates an new instance. + public QumuloIdentity() + { + + } + } + public partial interface IQumuloIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// Name of the File System resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + string FileSystemName { get; set; } + /// Resource identity path + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource identity path", + SerializedName = @"id", + PossibleTypes = new [] { typeof(string) })] + string Id { get; set; } + /// The name of the resource group. The name is case insensitive. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + 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. The value must be an UUID. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + string SubscriptionId { get; set; } + + } + internal partial interface IQumuloIdentityInternal + + { + /// Name of the File System resource + string FileSystemName { 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. The value must be an UUID. + string SubscriptionId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.json.cs new file mode 100644 index 00000000000..b042891e46c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/QumuloIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class QumuloIdentity + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new QumuloIdentity(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal QumuloIdentity(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_subscriptionId = If( json?.PropertyT("subscriptionId"), out var __jsonSubscriptionId) ? (string)__jsonSubscriptionId : (string)_subscriptionId;} + {_resourceGroupName = If( json?.PropertyT("resourceGroupName"), out var __jsonResourceGroupName) ? (string)__jsonResourceGroupName : (string)_resourceGroupName;} + {_fileSystemName = If( json?.PropertyT("fileSystemName"), out var __jsonFileSystemName) ? (string)__jsonFileSystemName : (string)_fileSystemName;} + {_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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._subscriptionId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._subscriptionId.ToString()) : null, "subscriptionId" ,container.Add ); + AddIf( null != (((object)this._resourceGroupName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._resourceGroupName.ToString()) : null, "resourceGroupName" ,container.Add ); + AddIf( null != (((object)this._fileSystemName)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._fileSystemName.ToString()) : null, "fileSystemName" ,container.Add ); + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.PowerShell.cs new file mode 100644 index 00000000000..895341d72ce --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.PowerShell.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial class Resource + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new Resource(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new Resource(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal Resource(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal Resource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + [System.ComponentModel.TypeConverter(typeof(ResourceTypeConverter))] + public partial interface IResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.TypeConverter.cs new file mode 100644 index 00000000000..5a070fc9624 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class ResourceTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return Resource.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return Resource.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return Resource.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.cs new file mode 100644 index 00000000000..84d17758565 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.cs @@ -0,0 +1,237 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Id { get => this._id; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Id { get => this._id; set { {_id = value;} } } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Name { get => this._name; set { {_name = value;} } } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemData()); set { {_systemData = value;} } } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Type { get => this._type; set { {_type = value;} } } + + /// Backing field for property. + private string _name; + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Name { get => this._name; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData _systemData; + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData SystemData { get => (this._systemData = this._systemData ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemData()); } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).CreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inlined)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)SystemData).LastModifiedByType = value ?? null; } + + /// Backing field for property. + private string _type; + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Type { get => this._type; } + + /// Creates an new instance. + public Resource() + { + + } + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + public partial interface IResource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + 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.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The name of the resource", + SerializedName = @"name", + PossibleTypes = new [] { typeof(string) })] + string Name { get; } + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataCreatedAt { get; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataCreatedBy { get; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? SystemDataLastModifiedAt { get; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string SystemDataLastModifiedBy { get; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The type of the resource. E.g. ""Microsoft.Compute/virtualMachines"" or ""Microsoft.Storage/storageAccounts""", + SerializedName = @"type", + PossibleTypes = new [] { typeof(string) })] + string Type { get; } + + } + /// Common fields that are returned in the response for all Azure Resource Manager resources + internal partial interface IResourceInternal + + { + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + string Id { get; set; } + /// The name of the resource + string Name { get; set; } + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData SystemData { get; set; } + /// The timestamp of resource creation (UTC). + global::System.DateTime? SystemDataCreatedAt { get; set; } + /// The identity that created the resource. + string SystemDataCreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataCreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? SystemDataLastModifiedAt { get; set; } + /// The identity that last modified the resource. + string SystemDataLastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string SystemDataLastModifiedByType { get; set; } + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + string Type { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.json.cs new file mode 100644 index 00000000000..e2e134f2480 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Resource.json.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Common fields that are returned in the response for all Azure Resource Manager resources + /// + public partial class Resource + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new Resource(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal Resource(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_systemData = If( json?.PropertyT("systemData"), out var __jsonSystemData) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemData.FromJson(__jsonSystemData) : _systemData;} + {_id = If( json?.PropertyT("id"), out var __jsonId) ? (string)__jsonId : (string)_id;} + {_name = If( json?.PropertyT("name"), out var __jsonName) ? (string)__jsonName : (string)_name;} + {_type = If( json?.PropertyT("type"), out var __jsonType) ? (string)__jsonType : (string)_type;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != this._systemData ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._systemData.ToJson(null,serializationMode) : null, "systemData" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.PowerShell.cs new file mode 100644 index 00000000000..7f90ba106b4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.PowerShell.cs @@ -0,0 +1,202 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial class SystemData + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new SystemData(content); + } + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new SystemData(content); + } + + /// + /// Creates a new instance of , deserializing the content from a json string. + /// + /// a string containing a JSON serialized instance of this model. + /// an instance of the model class. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal SystemData(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal SystemData(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("CreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedBy = (string) content.GetValueForProperty("CreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedBy, global::System.Convert.ToString); + } + if (content.Contains("CreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedByType = (string) content.GetValueForProperty("CreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedByType, global::System.Convert.ToString); + } + if (content.Contains("CreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedAt = (global::System.DateTime?) content.GetValueForProperty("CreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).CreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("LastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedBy = (string) content.GetValueForProperty("LastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedByType = (string) content.GetValueForProperty("LastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("LastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("LastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal)this).LastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + AfterDeserializePSObject(content); + } + + /// Serializes this instance to a json string. + + /// a containing this model serialized to JSON text. + public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Metadata pertaining to creation and last modification of the resource. + [System.ComponentModel.TypeConverter(typeof(SystemDataTypeConverter))] + public partial interface ISystemData + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.TypeConverter.cs new file mode 100644 index 00000000000..69215b2ed5e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class SystemDataTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return SystemData.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return SystemData.DeserializeFromDictionary(sourceValue); + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.cs new file mode 100644 index 00000000000..4898027613b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.cs @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemDataInternal + { + + /// Backing field for property. + private global::System.DateTime? _createdAt; + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public global::System.DateTime? CreatedAt { get => this._createdAt; set => this._createdAt = value; } + + /// Backing field for property. + private string _createdBy; + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string CreatedBy { get => this._createdBy; set => this._createdBy = value; } + + /// Backing field for property. + private string _createdByType; + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string CreatedByType { get => this._createdByType; set => this._createdByType = value; } + + /// Backing field for property. + private global::System.DateTime? _lastModifiedAt; + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public global::System.DateTime? LastModifiedAt { get => this._lastModifiedAt; set => this._lastModifiedAt = value; } + + /// Backing field for property. + private string _lastModifiedBy; + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string LastModifiedBy { get => this._lastModifiedBy; set => this._lastModifiedBy = value; } + + /// Backing field for property. + private string _lastModifiedByType; + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string LastModifiedByType { get => this._lastModifiedByType; set => this._lastModifiedByType = value; } + + /// Creates an new instance. + public SystemData() + { + + } + } + /// Metadata pertaining to creation and last modification of the resource. + public partial interface ISystemData : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource creation (UTC).", + SerializedName = @"createdAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that created the resource.", + SerializedName = @"createdBy", + PossibleTypes = new [] { typeof(string) })] + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that created the resource.", + SerializedName = @"createdByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The timestamp of resource last modification (UTC)", + SerializedName = @"lastModifiedAt", + PossibleTypes = new [] { typeof(global::System.DateTime) })] + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The identity that last modified the resource.", + SerializedName = @"lastModifiedBy", + PossibleTypes = new [] { typeof(string) })] + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"The type of identity that last modified the resource.", + SerializedName = @"lastModifiedByType", + PossibleTypes = new [] { typeof(string) })] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } + /// Metadata pertaining to creation and last modification of the resource. + internal partial interface ISystemDataInternal + + { + /// The timestamp of resource creation (UTC). + global::System.DateTime? CreatedAt { get; set; } + /// The identity that created the resource. + string CreatedBy { get; set; } + /// The type of identity that created the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string CreatedByType { get; set; } + /// The timestamp of resource last modification (UTC) + global::System.DateTime? LastModifiedAt { get; set; } + /// The identity that last modified the resource. + string LastModifiedBy { get; set; } + /// The type of identity that last modified the resource. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PSArgumentCompleterAttribute("User", "Application", "ManagedIdentity", "Key")] + string LastModifiedByType { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.json.cs new file mode 100644 index 00000000000..7b94720b71e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/SystemData.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Metadata pertaining to creation and last modification of the resource. + public partial class SystemData + { + + /// + /// AfterFromJson will be called after the json deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JsonNode that should be deserialized into this object. + + partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new SystemData(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal SystemData(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_createdBy = If( json?.PropertyT("createdBy"), out var __jsonCreatedBy) ? (string)__jsonCreatedBy : (string)_createdBy;} + {_createdByType = If( json?.PropertyT("createdByType"), out var __jsonCreatedByType) ? (string)__jsonCreatedByType : (string)_createdByType;} + {_createdAt = If( json?.PropertyT("createdAt"), out var __jsonCreatedAt) ? global::System.DateTime.TryParse((string)__jsonCreatedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonCreatedAtValue) ? __jsonCreatedAtValue : _createdAt : _createdAt;} + {_lastModifiedBy = If( json?.PropertyT("lastModifiedBy"), out var __jsonLastModifiedBy) ? (string)__jsonLastModifiedBy : (string)_lastModifiedBy;} + {_lastModifiedByType = If( json?.PropertyT("lastModifiedByType"), out var __jsonLastModifiedByType) ? (string)__jsonLastModifiedByType : (string)_lastModifiedByType;} + {_lastModifiedAt = If( json?.PropertyT("lastModifiedAt"), out var __jsonLastModifiedAt) ? global::System.DateTime.TryParse((string)__jsonLastModifiedAt, global::System.Globalization.CultureInfo.InvariantCulture, global::System.Globalization.DateTimeStyles.AdjustToUniversal, out var __jsonLastModifiedAtValue) ? __jsonLastModifiedAtValue : _lastModifiedAt : _lastModifiedAt;} + AfterFromJson(json); + } + + /// + /// Serializes this instance of into a . + /// + /// The container to serialize this object into. If the caller + /// passes in null, a new instance will be created and returned to the caller. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// a serialized instance of as a . + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._createdBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._createdBy.ToString()) : null, "createdBy" ,container.Add ); + AddIf( null != (((object)this._createdByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._createdByType.ToString()) : null, "createdByType" ,container.Add ); + AddIf( null != this._createdAt ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._createdAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "createdAt" ,container.Add ); + AddIf( null != (((object)this._lastModifiedBy)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._lastModifiedBy.ToString()) : null, "lastModifiedBy" ,container.Add ); + AddIf( null != (((object)this._lastModifiedByType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._lastModifiedByType.ToString()) : null, "lastModifiedByType" ,container.Add ); + AddIf( null != this._lastModifiedAt ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._lastModifiedAt?.ToString(@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK",global::System.Globalization.CultureInfo.InvariantCulture)) : null, "lastModifiedAt" ,container.Add ); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.PowerShell.cs new file mode 100644 index 00000000000..6d10505608b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// Resource tags. + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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.Qumulo.Models.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.Qumulo.Models.ITags FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 + // 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 Tags(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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + } + /// Resource tags. + [System.ComponentModel.TypeConverter(typeof(TagsTypeConverter))] + public partial interface ITags + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.TypeConverter.cs new file mode 100644 index 00000000000..84f0e1851ee --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.TypeConverter.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.cs new file mode 100644 index 00000000000..8693931b4bc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Resource tags. + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITagsInternal + { + + /// Creates an new instance. + public Tags() + { + + } + } + /// Resource tags. + public partial interface ITags : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray + { + + } + /// Resource tags. + internal partial interface ITagsInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.dictionary.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.dictionary.cs new file mode 100644 index 00000000000..81083a68585 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class Tags : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.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.Qumulo.Models.Tags source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.json.cs new file mode 100644 index 00000000000..cb3e2f7394a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/Tags.json.cs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// Resource tags. + 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new Tags(json) : null; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + /// + internal Tags(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.PowerShell.cs new file mode 100644 index 00000000000..2feb063f3f3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.PowerShell.cs @@ -0,0 +1,252 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + [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); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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.Qumulo.Models.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.Qumulo.Models.ITrackedResource FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// 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 + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializeDictionary(content); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Management.Automation.PSObject content that should be used. + internal TrackedResource(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Tag")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) content.GetValueForProperty("Tag",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Tag, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.TagsTypeConverter.ConvertFrom); + } + if (content.Contains("Location")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location = (string) content.GetValueForProperty("Location",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal)this).Location, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy = (string) content.GetValueForProperty("SystemDataCreatedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType = (string) content.GetValueForProperty("SystemDataCreatedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataCreatedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataCreatedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataCreatedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemDataLastModifiedBy")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy = (string) content.GetValueForProperty("SystemDataLastModifiedBy",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedBy, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedByType")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType = (string) content.GetValueForProperty("SystemDataLastModifiedByType",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedByType, global::System.Convert.ToString); + } + if (content.Contains("SystemDataLastModifiedAt")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt = (global::System.DateTime?) content.GetValueForProperty("SystemDataLastModifiedAt",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemDataLastModifiedAt, (v) => v is global::System.DateTime _v ? _v : global::System.Xml.XmlConvert.ToDateTime( v.ToString() , global::System.Xml.XmlDateTimeSerializationMode.Unspecified)); + } + if (content.Contains("SystemData")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData) content.GetValueForProperty("SystemData",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).SystemData, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.SystemDataTypeConverter.ConvertFrom); + } + if (content.Contains("Id")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id = (string) content.GetValueForProperty("Id",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Id, global::System.Convert.ToString); + } + if (content.Contains("Name")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name = (string) content.GetValueForProperty("Name",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Name, global::System.Convert.ToString); + } + if (content.Contains("Type")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type = (string) content.GetValueForProperty("Type",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)this).Type, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + [System.ComponentModel.TypeConverter(typeof(TrackedResourceTypeConverter))] + public partial interface ITrackedResource + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs new file mode 100644 index 00000000000..98d005ea35b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.cs new file mode 100644 index 00000000000..54dc4487707 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.cs @@ -0,0 +1,150 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + public partial class TrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResourceInternal, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IValidates + { + /// + /// Backing field for Inherited model + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource __resource = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Resource(); + + /// + /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Id; } + + /// Backing field for property. + private string _location; + + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Location { get => this._location; set => this._location = value; } + + /// Internal Acessors for Id + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Id { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Id; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Id = value; } + + /// Internal Acessors for Name + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Name; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Name = value; } + + /// Internal Acessors for SystemData + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemData; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemData = value; } + + /// Internal Acessors for Type + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal.Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Type; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Type = value; } + + /// The name of the resource + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Name { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).Name; } + + /// + /// Azure Resource Manager metadata containing createdBy and modifiedBy information. + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + internal Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ISystemData SystemData { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemData; } + + /// The timestamp of resource creation (UTC). + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataCreatedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedAt = value ?? default(global::System.DateTime); } + + /// The identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataCreatedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedBy = value ?? null; } + + /// The type of identity that created the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataCreatedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataCreatedByType = value ?? null; } + + /// The timestamp of resource last modification (UTC) + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public global::System.DateTime? SystemDataLastModifiedAt { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedAt; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedAt = value ?? default(global::System.DateTime); } + + /// The identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedBy { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedBy; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedBy = value ?? null; } + + /// The type of identity that last modified the resource. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string SystemDataLastModifiedByType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedByType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal)__resource).SystemDataLastModifiedByType = value ?? null; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags _tag; + + /// Resource tags. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => (this._tag = this._tag ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Tags()); set => this._tag = value; } + + /// + /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + /// + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Inherited)] + public string Type { get => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.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 that will be complete when validation is completed. + /// + public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener) + { + await eventListener.AssertNotNull(nameof(__resource), __resource); + await eventListener.AssertObjectIsValid(nameof(__resource), __resource); + } + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + public partial interface ITrackedResource : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResource + { + /// The geo-location where the resource lives + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = 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.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get; set; } + + } + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + internal partial interface ITrackedResourceInternal : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IResourceInternal + { + /// The geo-location where the resource lives + string Location { get; set; } + /// Resource tags. + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.json.cs new file mode 100644 index 00000000000..b8f2b6649d8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/TrackedResource.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' + /// + 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITrackedResource FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + __resource?.ToJson(container, serializationMode); + AddIf( null != this._tag ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) this._tag.ToJson(null,serializationMode) : null, "tags" ,container.Add ); + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)||serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate)) + { + AddIf( null != (((object)this._location)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._location.ToString()) : null, "location" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal TrackedResource(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + __resource = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Resource(json); + {_tag = If( json?.PropertyT("tags"), out var __jsonTags) ? Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.Tags.FromJson(__jsonTags) : _tag;} + {_location = If( json?.PropertyT("location"), out var __jsonLocation) ? (string)__jsonLocation : (string)_location;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.cs new file mode 100644 index 00000000000..5b4a7b46cba --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.PowerShell.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// The identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesTypeConverter))] + public partial class UserAssignedIdentities + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentities(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.Qumulo.Models.IUserAssignedIdentities DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentities(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.Qumulo.Models.IUserAssignedIdentities FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentities(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 UserAssignedIdentities(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 identities assigned to this resource by the user. + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentitiesTypeConverter))] + public partial interface IUserAssignedIdentities + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs new file mode 100644 index 00000000000..8944ed0f08f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentitiesTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentities.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentities.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentities.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.cs new file mode 100644 index 00000000000..f7f3b579410 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.cs @@ -0,0 +1,33 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class UserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentitiesInternal + { + + /// Creates an new instance. + public UserAssignedIdentities() + { + + } + } + /// The identities assigned to this resource by the user. + public partial interface IUserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray + { + + } + /// The identities assigned to this resource by the user. + internal partial interface IUserAssignedIdentitiesInternal + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs new file mode 100644 index 00000000000..bf45deb43dd --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.dictionary.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + public partial class UserAssignedIdentities : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray + { + protected global::System.Collections.Generic.Dictionary __additionalProperties = new global::System.Collections.Generic.Dictionary(); + + global::System.Collections.Generic.IDictionary Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.AdditionalProperties { get => __additionalProperties; } + + int Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.Count { get => __additionalProperties.Count; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.Keys { get => __additionalProperties.Keys; } + + global::System.Collections.Generic.IEnumerable Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray.Values { get => __additionalProperties.Values; } + + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity this[global::System.String index] { get => __additionalProperties[index]; set => __additionalProperties[index] = value; } + + /// + /// + public void Add(global::System.String key, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity 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.Qumulo.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.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity value) => __additionalProperties.TryGetValue( key, out value); + + /// + + public static implicit operator global::System.Collections.Generic.Dictionary(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentities source) => source.__additionalProperties; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.json.cs new file mode 100644 index 00000000000..2f8291701c7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentities.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// The identities assigned to this resource by the user. + public partial class UserAssignedIdentities + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentities FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new UserAssignedIdentities(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray)this).AdditionalProperties, container); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + /// + internal UserAssignedIdentities(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IAssociativeArray)this).AdditionalProperties, (j) => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity.FromJson(j) ,exclusions ); + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs new file mode 100644 index 00000000000..28c764fc5f6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.PowerShell.cs @@ -0,0 +1,170 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// User assigned identity properties + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityTypeConverter))] + public partial class UserAssignedIdentity + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserAssignedIdentity(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.Qumulo.Models.IUserAssignedIdentity DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserAssignedIdentity(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.Qumulo.Models.IUserAssignedIdentity FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserAssignedIdentity(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).ClientId, 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 UserAssignedIdentity(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("PrincipalId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).PrincipalId = (string) content.GetValueForProperty("PrincipalId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).PrincipalId, global::System.Convert.ToString); + } + if (content.Contains("ClientId")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).ClientId = (string) content.GetValueForProperty("ClientId",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal)this).ClientId, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// User assigned identity properties + [System.ComponentModel.TypeConverter(typeof(UserAssignedIdentityTypeConverter))] + public partial interface IUserAssignedIdentity + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs new file mode 100644 index 00000000000..b93ba330a8b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserAssignedIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserAssignedIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserAssignedIdentity.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserAssignedIdentity.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.cs new file mode 100644 index 00000000000..789567782f8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal + { + + /// Backing field for property. + private string _clientId; + + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string ClientId { get => this._clientId; } + + /// Internal Acessors for ClientId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal.ClientId { get => this._clientId; set { {_clientId = value;} } } + + /// Internal Acessors for PrincipalId + string Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentityInternal.PrincipalId { get => this._principalId; set { {_principalId = value;} } } + + /// Backing field for property. + private string _principalId; + + /// The principal ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string PrincipalId { get => this._principalId; } + + /// Creates an new instance. + public UserAssignedIdentity() + { + + } + } + /// User assigned identity properties + public partial interface IUserAssignedIdentity : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// The client ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The client ID of the assigned identity.", + SerializedName = @"clientId", + PossibleTypes = new [] { typeof(string) })] + string ClientId { get; } + /// The principal ID of the assigned identity. + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = true, + Read = true, + Create = false, + Update = false, + Description = @"The principal ID of the assigned identity.", + SerializedName = @"principalId", + PossibleTypes = new [] { typeof(string) })] + string PrincipalId { get; } + + } + /// User assigned identity properties + internal partial interface IUserAssignedIdentityInternal + + { + /// The client ID of the assigned identity. + string ClientId { get; set; } + /// The principal ID of the assigned identity. + string PrincipalId { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.json.cs new file mode 100644 index 00000000000..c503f04f596 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserAssignedIdentity.json.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// User assigned identity properties + public partial class UserAssignedIdentity + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity. + /// + /// a to deserialize from. + /// + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserAssignedIdentity FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new UserAssignedIdentity(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._principalId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._principalId.ToString()) : null, "principalId" ,container.Add ); + } + if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeRead)) + { + AddIf( null != (((object)this._clientId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._clientId.ToString()) : null, "clientId" ,container.Add ); + } + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal UserAssignedIdentity(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_principalId = If( json?.PropertyT("principalId"), out var __jsonPrincipalId) ? (string)__jsonPrincipalId : (string)_principalId;} + {_clientId = If( json?.PropertyT("clientId"), out var __jsonClientId) ? (string)__jsonClientId : (string)_clientId;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.PowerShell.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.PowerShell.cs new file mode 100644 index 00000000000..3f248c786fe --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.PowerShell.cs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// User Details of Qumulo FileSystem resource + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial class UserDetails + { + + /// + /// AfterDeserializeDictionary will be called after the deserialization has finished, allowing customization of the + /// object before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Collections.IDictionary content that should be used. + + partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); + + /// + /// AfterDeserializePSObject will be called after the deserialization has finished, allowing customization of the object + /// before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The global::System.Management.Automation.PSObject content that should be used. + + partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); + + /// + /// BeforeDeserializeDictionary will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Collections.IDictionary content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); + + /// + /// BeforeDeserializePSObject will be called before the deserialization has commenced, allowing complete customization + /// of the object before it is deserialized. + /// If you wish to disable the default deserialization entirely, return true in the output + /// parameter. + /// Implement this method in a partial class to enable this behavior. + /// + /// The global::System.Management.Automation.PSObject content that should be used. + /// Determines if the rest of the serialization should be processed, or if the method should return + /// instantly. + + partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); + + /// + /// OverrideToString will be called if it is implemented. Implement this method in a partial class to enable this behavior + /// + /// /// instance serialized to a string, normally it is a Json + /// /// set returnNow to true if you provide a customized OverrideToString function + + partial void OverrideToString(ref string stringResult, ref bool returnNow); + + /// + /// Deserializes a into an instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + /// + /// an instance of . + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails DeserializeFromDictionary(global::System.Collections.IDictionary content) + { + return new UserDetails(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.Qumulo.Models.IUserDetails DeserializeFromPSObject(global::System.Management.Automation.PSObject content) + { + return new UserDetails(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.Qumulo.Models.IUserDetails FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SerializationMode.IncludeAll)?.ToString(); + + public override string ToString() + { + var returnNow = false; + var result = global::System.String.Empty; + OverrideToString(ref result, ref returnNow); + if (returnNow) + { + return result; + } + return ToJsonString(); + } + + /// + /// Deserializes a into a new instance of . + /// + /// The global::System.Collections.IDictionary content that should be used. + internal UserDetails(global::System.Collections.IDictionary content) + { + bool returnNow = false; + BeforeDeserializeDictionary(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Email")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)this).Email = (string) content.GetValueForProperty("Email",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)this).Email, 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 UserDetails(global::System.Management.Automation.PSObject content) + { + bool returnNow = false; + BeforeDeserializePSObject(content, ref returnNow); + if (returnNow) + { + return; + } + // actually deserialize + if (content.Contains("Email")) + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)this).Email = (string) content.GetValueForProperty("Email",((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal)this).Email, global::System.Convert.ToString); + } + AfterDeserializePSObject(content); + } + } + /// User Details of Qumulo FileSystem resource + [System.ComponentModel.TypeConverter(typeof(UserDetailsTypeConverter))] + public partial interface IUserDetails + + { + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.TypeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.TypeConverter.cs new file mode 100644 index 00000000000..f587bb4dbc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.TypeConverter.cs @@ -0,0 +1,145 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + + /// + /// A PowerShell PSTypeConverter to support converting to an instance of + /// + public partial class UserDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to the + /// type. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the + /// parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return UserDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; + } + catch + { + // Unable to use JSON pattern + } + if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return UserDetails.DeserializeFromPSObject(sourceValue); + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return UserDetails.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.cs new file mode 100644 index 00000000000..99cd0d2c678 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// User Details of Qumulo FileSystem resource + public partial class UserDetails : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetailsInternal + { + + /// Backing field for property. + private string _email; + + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Origin(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.PropertyOrigin.Owned)] + public string Email { get => this._email; set => this._email = value; } + + /// Creates an new instance. + public UserDetails() + { + + } + } + /// User Details of Qumulo FileSystem resource + public partial interface IUserDetails : + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IJsonSerializable + { + /// User Email + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Read = true, + Create = true, + Update = true, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + string Email { get; set; } + + } + /// User Details of Qumulo FileSystem resource + internal partial interface IUserDetailsInternal + + { + /// User Email + string Email { get; set; } + + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.json.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.json.cs new file mode 100644 index 00000000000..008738d102c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/Models/UserDetails.json.cs @@ -0,0 +1,104 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// User Details of Qumulo FileSystem resource + public partial class UserDetails + { + + /// + /// 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.Qumulo.Runtime.Json.JsonObject json); + + /// + /// AfterToJson will be called after the json serialization has finished, allowing customization of the before it is returned. Implement this method in a partial class to enable this behavior + /// + /// The JSON container that the serialization result will be placed in. + + partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonObject container, ref bool returnNow); + + /// + /// Deserializes a into an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails. + /// + /// a to deserialize from. + /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails. + public static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IUserDetails FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json ? new UserDetails(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.Qumulo.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode) + { + container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject(); + + bool returnNow = false; + BeforeToJson(ref container, ref returnNow); + if (returnNow) + { + return container; + } + AddIf( null != (((object)this._email)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonString(this._email.ToString()) : null, "email" ,container.Add ); + AfterToJson(ref container); + return container; + } + + /// + /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject into a new instance of . + /// + /// A Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject instance to deserialize from. + internal UserDetails(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject json) + { + bool returnNow = false; + BeforeFromJson(json, ref returnNow); + if (returnNow) + { + return; + } + {_email = If( json?.PropertyT("email"), out var __jsonEmail) ? (string)__jsonEmail : (string)_email;} + AfterFromJson(json); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/QumuloStorage.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/QumuloStorage.cs new file mode 100644 index 00000000000..ec1114da582 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/api/QumuloStorage.cs @@ -0,0 +1,2577 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + + /// + /// Low-level API implementation for the Qumulo.Storage service. + /// + public partial class QumuloStorage + { + + /// update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Resource create parameters. + /// 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.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsCreateOrUpdate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FileSystemResource + /// + /// Resource create parameters. + /// 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.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FileSystemResource + /// + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsCreateOrUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Json string supplied to the FileSystemsCreateOrUpdate operation + /// 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.Qumulo.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 FileSystemsCreateOrUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsCreateOrUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Json string supplied to the FileSystemsCreateOrUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsCreateOrUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Resource create parameters. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsCreateOrUpdateWithResult(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Put, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsCreateOrUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsCreateOrUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + // 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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Qumulo.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsCreateOrUpdate_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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Qumulo.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Resource create parameters. + /// 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 FileSystemsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(fileSystemName),fileSystemName); + await eventListener.AssertRegEx(nameof(fileSystemName), fileSystemName, @"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// Delete a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Qumulo.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 FileSystemsDelete(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Delete a FileSystemResource + /// + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Qumulo.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 FileSystemsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Delete, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsDelete_Call (request, onNoContent,onOk,onDefault,eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 204 (NoContent). + /// 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.Qumulo.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 FileSystemsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func onNoContent, global::System.Func onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 0); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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"); + var operationLocation = _response.GetFirstHeader(@"Operation-Location"); + while (request.Method == System.Net.Http.HttpMethod.Put && _response.StatusCode == global::System.Net.HttpStatusCode.OK || _response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) + { + // delay before making the next polling request + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // 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"); + } + if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Operation-Location"))) { + operationLocation = _response.GetFirstHeader(@"Operation-Location"); + } + var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? global::System.String.IsNullOrEmpty(operationLocation) ? _originalUri : operationLocation : location : asyncOperation; + request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(); + + // drop the old response + _response?.Dispose(); + + // make the polling call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + + // if we got back an OK, take a peek inside and see if it's done + if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) + { + var error = false; + try { + if( Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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; + } + + switch( state?.ToString()?.ToLower() ) + { + case "failed": + error = true; + break; + case "succeeded": + 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. + } + if (error) { + throw new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.UndeclaredResponseException(_response); + } + } + + // 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.Qumulo.Runtime.Method.Get); + + // drop the old response + _response?.Dispose(); + + // make the final call + _response = await sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Polling, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + break; + } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onNoContent(_response); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System 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 FileSystemsDelete_Validate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(fileSystemName),fileSystemName); + await eventListener.AssertRegEx(nameof(fileSystemName), fileSystemName, @"^[a-zA-Z0-9_-]*$"); + } + } + + /// Get a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System 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.Qumulo.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 FileSystemsGet(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FileSystemResource + /// + /// 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.Qumulo.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 FileSystemsGetViaIdentity(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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsGet_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Get a FileSystemResource + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsGetViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Get a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsGetWithResult(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsGetWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsGetWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsGet_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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System 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 FileSystemsGet_Validate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(fileSystemName),fileSystemName); + await eventListener.AssertRegEx(nameof(fileSystemName), fileSystemName, @"^[a-zA-Z0-9_-]*$"); + } + } + + /// List FileSystemResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// 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.Qumulo.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 FileSystemsListByResourceGroup(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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FileSystemResource resources by 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.Qumulo.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 FileSystemsListByResourceGroupViaIdentity(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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems$", 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/Qumulo.Storage/fileSystems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsListByResourceGroup_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FileSystemResource resources by resource group + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListByResourceGroupViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems$", 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/Qumulo.Storage/fileSystems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// List FileSystemResource resources by resource group + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListByResourceGroupWithResult(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsListByResourceGroupWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListByResourceGroupWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListByResourceGroup_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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// 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 FileSystemsListByResourceGroup_Validate(string subscriptionId, string resourceGroupName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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\._\(\)]+$"); + } + } + + /// List FileSystemResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// 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.Qumulo.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 FileSystemsListBySubscription(string subscriptionId, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FileSystemResource resources by subscription ID + /// + /// 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.Qumulo.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 FileSystemsListBySubscriptionViaIdentity(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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Qumulo.Storage/fileSystems$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Qumulo.Storage/fileSystems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsListBySubscription_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List FileSystemResource resources by subscription ID + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListBySubscriptionViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?[^/]+)/providers/Qumulo.Storage/fileSystems$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/providers/Qumulo.Storage/fileSystems'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// List FileSystemResource resources by subscription ID + /// The ID of the target subscription. The value must be an UUID. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListBySubscriptionWithResult(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/providers/Qumulo.Storage/fileSystems" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsListBySubscriptionWithResult_Call (request, eventListener,sender); + } + } + + /// + /// Actual wire call for method. + /// + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListBySubscriptionWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsListBySubscription_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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResourceListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// 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 FileSystemsListBySubscription_Validate(string subscriptionId, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); + } + } + + /// Update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// The resource properties to be updated. + /// 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.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsUpdate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a FileSystemResource + /// + /// The resource properties to be updated. + /// 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.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate body, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a FileSystemResource + /// + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsUpdateViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // 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/Qumulo.Storage/fileSystems/(?[^/]+)$", 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/Qumulo.Storage/fileSystems/{fileSystemName}'"); + } + + // replace URI parameters with values from identity + var subscriptionId = _match.Groups["subscriptionId"].Value; + var resourceGroupName = _match.Groups["resourceGroupName"].Value; + var fileSystemName = _match.Groups["fileSystemName"].Value; + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + subscriptionId + + "/resourceGroups/" + + resourceGroupName + + "/providers/Qumulo.Storage/fileSystems/" + + fileSystemName + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Json string supplied to the FileSystemsUpdate operation + /// 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.Qumulo.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 FileSystemsUpdateViaJsonString(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.String jsonString, global::System.Func, global::System.Threading.Tasks.Task> onOk, global::System.Func, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.FileSystemsUpdate_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// Update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// Json string supplied to the FileSystemsUpdate operation + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsUpdateViaJsonStringWithResult(string subscriptionId, string resourceGroupName, string fileSystemName, global::System.String jsonString, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(jsonString, global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Update a FileSystemResource + /// The ID of the target subscription. The value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// The resource properties to be updated. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// Allows the caller to choose the depth of the serialization. See . + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task FileSystemsUpdateWithResult(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode serializationMode = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/subscriptions/" + + global::System.Uri.EscapeDataString(subscriptionId) + + "/resourceGroups/" + + global::System.Uri.EscapeDataString(resourceGroupName) + + "/providers/Qumulo.Storage/fileSystems/" + + global::System.Uri.EscapeDataString(fileSystemName) + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Patch, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // set body content + request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null, serializationMode).ToString() : @"{}", global::System.Text.Encoding.UTF8); + request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BodyContentSet); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.FileSystemsUpdateWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsUpdateWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers)); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 FileSystemsUpdate_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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) .ReadHeaders(_response.Headers))); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 value must be an UUID. + /// The name of the resource group. The name is case insensitive. + /// Name of the File System resource + /// The resource properties to be updated. + /// 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 FileSystemsUpdate_Validate(string subscriptionId, string resourceGroupName, string fileSystemName, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceUpdate body, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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(fileSystemName),fileSystemName); + await eventListener.AssertRegEx(nameof(fileSystemName), fileSystemName, @"^[a-zA-Z0-9_-]*$"); + await eventListener.AssertNotNull(nameof(body), body); + await eventListener.AssertObjectIsValid(nameof(body), body); + } + } + + /// List the operations for the 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.Qumulo.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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Qumulo.Storage/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the 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.Qumulo.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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Qumulo.Storage/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Qumulo.Storage/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Qumulo.Storage/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return; } + // make the call + await this.OperationsList_Call (request, onOk,onDefault,eventListener,sender); + } + } + + /// List the operations for the provider + /// + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListViaIdentityWithResult(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // verify that Identity format is an exact match for uri + + var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Qumulo.Storage/operations$", global::System.Text.RegularExpressions.RegexOptions.IgnoreCase).Match(viaIdentity); + if (!_match.Success) + { + throw new global::System.Exception("Invalid identity for URI '/providers/Qumulo.Storage/operations'"); + } + + // replace URI parameters with values from identity + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Qumulo.Storage/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// List the operations for the provider + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + public async global::System.Threading.Tasks.Task OperationsListWithResult(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + var apiVersion = @"2024-06-19"; + // Constant Parameters + using( NoSynchronizationContext ) + { + // construct URL + var pathAndQuery = global::System.Text.RegularExpressions.Regex.Replace( + "/providers/Qumulo.Storage/operations" + + "?" + + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) + ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2"); + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.URLCreated, pathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + // generate request object + var _url = new global::System.Uri($"https://management.azure.com{pathAndQuery}"); + var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get, _url); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.RequestCreated, request.RequestUri.PathAndQuery); if( eventListener.Token.IsCancellationRequested ) { return null; } + + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.HeaderParametersAdded); if( eventListener.Token.IsCancellationRequested ) { return null; } + // make the call + return await this.OperationsListWithResult_Call (request, eventListener,sender); + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync pipeline to use to make the request. + /// + /// A that will be complete when handling of the response is completed. + /// + internal async global::System.Threading.Tasks.Task OperationsListWithResult_Call(global::System.Net.Http.HttpRequestMessage request, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return null; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + return await _result; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return null; } + var _result = _response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) ); + // Error Response : default + var code = (await _result)?.Code; + var message = (await _result)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(_response, await _result); + throw ex; + } + else + { + throw new global::System.Exception($"[{code}] : {message}"); + } + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Finally, request, _response); + _response?.Dispose(); + request?.Dispose(); + } + } + } + + /// Actual wire call for method. + /// the prepared HttpRequestMessage to send. + /// a delegate that is called when the remote service returns 200 (OK). + /// a delegate that is called when the remote service returns default (any response code not handled + /// elsewhere). + /// an instance that will receive events. + /// an instance of an Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.ISendAsync sender) + { + using( NoSynchronizationContext ) + { + global::System.Net.Http.HttpResponseMessage _response = null; + try + { + var sendTask = sender.SendAsync(request, eventListener); + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } + _response = await sendTask; + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Progress, "intentional placeholder", 100); if( eventListener.Token.IsCancellationRequested ) { return; } + var _contentType = _response.Content.Headers.ContentType?.MediaType; + + switch ( _response.StatusCode ) + { + case global::System.Net.HttpStatusCode.OK: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.OperationListResult.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + default: + { + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } + await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(body.Result)) )); + break; + } + } + } + finally + { + // finally statements + await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener eventListener) + { + using( NoSynchronizationContext ) + { + + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_Get.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_Get.cs new file mode 100644 index 00000000000..e8cc04f2690 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_Get.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// Get a FileSystemResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzQumuloFileSystem_Get")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"Get a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class GetAzQumuloFileSystem_Get : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string Name { get => this._name; set => this._name = value; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzQumuloFileSystem_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.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsGet(SubscriptionId, ResourceGroupName, Name, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_GetViaIdentity.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_GetViaIdentity.cs new file mode 100644 index 00000000000..1c8e7276f29 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_GetViaIdentity.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// Get a FileSystemResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzQumuloFileSystem_GetViaIdentity")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"Get a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class GetAzQumuloFileSystem_GetViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity 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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzQumuloFileSystem_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.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FileSystemsGetViaIdentity(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.FileSystemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FileSystemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FileSystemsGet(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FileSystemName ?? null, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List.cs new file mode 100644 index 00000000000..30c7d1cf19a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List.cs @@ -0,0 +1,518 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// List FileSystemResource resources by resource group + /// + /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzQumuloFileSystem_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"List FileSystemResource resources by resource group")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems", ApiVersion = "2024-06-19")] + public partial class GetAzQumuloFileSystem_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzQumuloFileSystem_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.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsListByResourceGroup(SubscriptionId, ResourceGroupName, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult + /// 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.Qumulo.Models.IFileSystemResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsListByResourceGroup_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List1.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List1.cs new file mode 100644 index 00000000000..34972663da0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloFileSystem_List1.cs @@ -0,0 +1,504 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// List FileSystemResource resources by subscription ID + /// + /// [OpenAPI] ListBySubscription=>GET:"/subscriptions/{subscriptionId}/providers/Qumulo.Storage/fileSystems" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzQumuloFileSystem_List1")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"List FileSystemResource resources by subscription ID")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/providers/Qumulo.Storage/fileSystems", ApiVersion = "2024-06-19")] + public partial class GetAzQumuloFileSystem_List1 : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Backing field for property. + private string[] _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzQumuloFileSystem_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.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + foreach( var SubscriptionId in this.SubscriptionId ) + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsListBySubscription(SubscriptionId, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResourceListResult + /// 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.Qumulo.Models.IFileSystemResourceListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsListBySubscription_Call(requestMessage, onOk, onDefault, this, Pipeline); + } + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloOperation_List.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloOperation_List.cs new file mode 100644 index 00000000000..5b35e87b21c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/GetAzQumuloOperation_List.cs @@ -0,0 +1,483 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// List the operations for the provider + /// + /// [OpenAPI] List=>GET:"/providers/Qumulo.Storage/operations" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzQumuloOperation_List")] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperation))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"List the operations for the provider")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/providers/Qumulo.Storage/operations", ApiVersion = "2024-06-19")] + public partial class GetAzQumuloOperation_List : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// A flag to tell whether it is the first onOK call. + private bool _isFirst = true; + + /// Link to retrieve next page. + private string _nextLink; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Wait for .NET debugger to attach + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public GetAzQumuloOperation_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.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Information: + { + var data = messageData(); + WriteInformation(data.Message, new string[]{}); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.OperationsList(onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnOk(responseMessage, response, ref _returnNow); + // if overrideOnOk has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // onOk - response for 200 / application/json + // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IOperationListResult + var result = (await response); + // response should be returning an array of some kind. +Pageable + // pageable / value / nextLink + if (null != result.Value) + { + if (0 == _responseSize && 1 == result.Value.Count) + { + _firstResponse = result.Value[0]; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + var values = new System.Collections.Generic.List(); + foreach( var value in result.Value ) + { + values.Add(value.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(values, true); + _responseSize = 2; + } + } + _nextLink = result.NextLink; + if (_isFirst) + { + _isFirst = false; + while (!String.IsNullOrEmpty(_nextLink)) + { + if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) + { + requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Method.Get ); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateExpanded.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateExpanded.cs new file mode 100644 index 00000000000..17b63283063 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateExpanded.cs @@ -0,0 +1,788 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// create a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzQumuloFileSystem_CreateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"create a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class NewAzQumuloFileSystem_CreateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Initial administrator password of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Initial administrator password of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + public string AdminPassword { get => _resourceBody.AdminPassword ?? null; set => _resourceBody.AdminPassword = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Availability zone + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Availability zone")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + public string AvailabilityZone { get => _resourceBody.AvailabilityZone ?? null; set => _resourceBody.AvailabilityZone = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// File system Id of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "File system Id of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + public string ClusterLoginUrl { get => _resourceBody.ClusterLoginUrl ?? null; set => _resourceBody.ClusterLoginUrl = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Delegated subnet id for Vnet injection + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Delegated subnet id for Vnet injection")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + public string DelegatedSubnetId { get => _resourceBody.DelegatedSubnetId ?? null; set => _resourceBody.DelegatedSubnetId = value; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public global::System.Management.Automation.SwitchParameter EnableSystemAssignedIdentity { set => _resourceBody.IdentityType = value.IsPresent ? "SystemAssigned": null ; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Marketplace Subscription Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace Subscription Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailMarketplaceSubscriptionId { get => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId = value; } + + /// Offer Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailOfferId { get => _resourceBody.MarketplaceDetailOfferId ?? null; set => _resourceBody.MarketplaceDetailOfferId = value; } + + /// Plan Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPlanId { get => _resourceBody.MarketplaceDetailPlanId ?? null; set => _resourceBody.MarketplaceDetailPlanId = value; } + + /// Publisher Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPublisherId { get => _resourceBody.MarketplaceDetailPublisherId ?? null; set => _resourceBody.MarketplaceDetailPublisherId = value; } + + /// Term Unit + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Unit")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailTermUnit { get => _resourceBody.MarketplaceDetailTermUnit ?? null; set => _resourceBody.MarketplaceDetailTermUnit = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline Pipeline { get; set; } + + /// Private IPs of the resource + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Private IPs of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + public string[] PrivateIP { get => _resourceBody.PrivateIP?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.PrivateIP = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Storage Sku + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Storage Sku")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + public string StorageSku { get => _resourceBody.StorageSku ?? null; set => _resourceBody.StorageSku = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// User Email + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User Email")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmail { get => _resourceBody.UserDetailEmail ?? null; set => _resourceBody.UserDetailEmail = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzQumuloFileSystem_CreateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.NewAzQumuloFileSystem_CreateExpanded Clone() + { + var clone = new NewAzQumuloFileSystem_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._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzQumuloFileSystem_CreateExpanded() + { + + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.FileSystemsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaIdentityExpanded.cs new file mode 100644 index 00000000000..20ab469ca88 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaIdentityExpanded.cs @@ -0,0 +1,766 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// create a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzQumuloFileSystem_CreateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"create a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class NewAzQumuloFileSystem_CreateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Initial administrator password of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Initial administrator password of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + public string AdminPassword { get => _resourceBody.AdminPassword ?? null; set => _resourceBody.AdminPassword = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Availability zone + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Availability zone")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + public string AvailabilityZone { get => _resourceBody.AvailabilityZone ?? null; set => _resourceBody.AvailabilityZone = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// File system Id of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "File system Id of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + public string ClusterLoginUrl { get => _resourceBody.ClusterLoginUrl ?? null; set => _resourceBody.ClusterLoginUrl = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Delegated subnet id for Vnet injection + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Delegated subnet id for Vnet injection")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + public string DelegatedSubnetId { get => _resourceBody.DelegatedSubnetId ?? null; set => _resourceBody.DelegatedSubnetId = value; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public global::System.Management.Automation.SwitchParameter EnableSystemAssignedIdentity { set => _resourceBody.IdentityType = value.IsPresent ? "SystemAssigned": null ; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity 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 = true, HelpMessage = "The geo-location where the resource lives")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Marketplace Subscription Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace Subscription Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailMarketplaceSubscriptionId { get => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId = value; } + + /// Offer Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailOfferId { get => _resourceBody.MarketplaceDetailOfferId ?? null; set => _resourceBody.MarketplaceDetailOfferId = value; } + + /// Plan Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPlanId { get => _resourceBody.MarketplaceDetailPlanId ?? null; set => _resourceBody.MarketplaceDetailPlanId = value; } + + /// Publisher Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPublisherId { get => _resourceBody.MarketplaceDetailPublisherId ?? null; set => _resourceBody.MarketplaceDetailPublisherId = value; } + + /// Term Unit + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Unit")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailTermUnit { get => _resourceBody.MarketplaceDetailTermUnit ?? null; set => _resourceBody.MarketplaceDetailTermUnit = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline Pipeline { get; set; } + + /// Private IPs of the resource + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Private IPs of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + public string[] PrivateIP { get => _resourceBody.PrivateIP?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.PrivateIP = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Storage Sku + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Storage Sku")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + public string StorageSku { get => _resourceBody.StorageSku ?? null; set => _resourceBody.StorageSku = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// User Email + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User Email")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmail { get => _resourceBody.UserDetailEmail ?? null; set => _resourceBody.UserDetailEmail = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzQumuloFileSystem_CreateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.NewAzQumuloFileSystem_CreateViaIdentityExpanded Clone() + { + var clone = new NewAzQumuloFileSystem_CreateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzQumuloFileSystem_CreateViaIdentityExpanded() + { + + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + this.PreProcessManagedIdentityParameters(); + await this.Client.FileSystemsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate); + } + 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.FileSystemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FileSystemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + this.PreProcessManagedIdentityParameters(); + await this.Client.FileSystemsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FileSystemName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonFilePath.cs new file mode 100644 index 00000000000..a3be22e3791 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonFilePath.cs @@ -0,0 +1,605 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// create a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzQumuloFileSystem_CreateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"create a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.NotSuggestDefaultParameterSet] + public partial class NewAzQumuloFileSystem_CreateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Create operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzQumuloFileSystem_CreateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.NewAzQumuloFileSystem_CreateViaJsonFilePath Clone() + { + var clone = new NewAzQumuloFileSystem_CreateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzQumuloFileSystem_CreateViaJsonFilePath() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonString.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonString.cs new file mode 100644 index 00000000000..a77a81ea721 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/NewAzQumuloFileSystem_CreateViaJsonString.cs @@ -0,0 +1,603 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// create a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.New, @"AzQumuloFileSystem_CreateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"create a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.NotSuggestDefaultParameterSet] + public partial class NewAzQumuloFileSystem_CreateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Create operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Create operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Create operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of NewAzQumuloFileSystem_CreateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.NewAzQumuloFileSystem_CreateViaJsonString Clone() + { + var clone = new NewAzQumuloFileSystem_CreateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public NewAzQumuloFileSystem_CreateViaJsonString() + { + + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_Delete.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_Delete.cs new file mode 100644 index 00000000000..af1f9044e09 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_Delete.cs @@ -0,0 +1,609 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// Delete a FileSystemResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzQumuloFileSystem_Delete", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"Delete a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class RemoveAzQumuloFileSystem_Delete : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzQumuloFileSystem_Delete + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.RemoveAzQumuloFileSystem_Delete Clone() + { + var clone = new RemoveAzQumuloFileSystem_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsDelete(SubscriptionId, ResourceGroupName, Name, onNoContent, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzQumuloFileSystem_Delete() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 / application/json + 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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_DeleteViaIdentity.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_DeleteViaIdentity.cs new file mode 100644 index 00000000000..575bdc7e78e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/RemoveAzQumuloFileSystem_DeleteViaIdentity.cs @@ -0,0 +1,586 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// Delete a FileSystemResource + /// + /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzQumuloFileSystem_DeleteViaIdentity", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(bool))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"Delete a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class RemoveAzQumuloFileSystem_DeleteViaIdentity : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity 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.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter PassThru { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// 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() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of RemoveAzQumuloFileSystem_DeleteViaIdentity + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.RemoveAzQumuloFileSystem_DeleteViaIdentity Clone() + { + var clone = new RemoveAzQumuloFileSystem_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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsDelete' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + await this.Client.FileSystemsDeleteViaIdentity(InputObject.Id, onNoContent, 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.FileSystemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FileSystemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + await this.Client.FileSystemsDelete(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FileSystemName ?? null, onNoContent, onOk, onDefault, this, Pipeline); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public RemoveAzQumuloFileSystem_DeleteViaIdentity() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 / application/json + 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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateExpanded.cs new file mode 100644 index 00000000000..b4960f0d68f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateExpanded.cs @@ -0,0 +1,789 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// update a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzQumuloFileSystem_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"update a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + public partial class SetAzQumuloFileSystem_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Initial administrator password of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Initial administrator password of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + public string AdminPassword { get => _resourceBody.AdminPassword ?? null; set => _resourceBody.AdminPassword = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Availability zone + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Availability zone")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + public string AvailabilityZone { get => _resourceBody.AvailabilityZone ?? null; set => _resourceBody.AvailabilityZone = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// File system Id of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "File system Id of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + public string ClusterLoginUrl { get => _resourceBody.ClusterLoginUrl ?? null; set => _resourceBody.ClusterLoginUrl = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Delegated subnet id for Vnet injection + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Delegated subnet id for Vnet injection")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + public string DelegatedSubnetId { get => _resourceBody.DelegatedSubnetId ?? null; set => _resourceBody.DelegatedSubnetId = value; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The geo-location where the resource lives", + SerializedName = @"location", + PossibleTypes = new [] { typeof(string) })] + public string Location { get => _resourceBody.Location ?? null; set => _resourceBody.Location = value; } + + /// Marketplace Subscription Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace Subscription Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailMarketplaceSubscriptionId { get => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId = value; } + + /// Offer Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailOfferId { get => _resourceBody.MarketplaceDetailOfferId ?? null; set => _resourceBody.MarketplaceDetailOfferId = value; } + + /// Plan Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPlanId { get => _resourceBody.MarketplaceDetailPlanId ?? null; set => _resourceBody.MarketplaceDetailPlanId = value; } + + /// Publisher Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPublisherId { get => _resourceBody.MarketplaceDetailPublisherId ?? null; set => _resourceBody.MarketplaceDetailPublisherId = value; } + + /// Term Unit + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Unit")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailTermUnit { get => _resourceBody.MarketplaceDetailTermUnit ?? null; set => _resourceBody.MarketplaceDetailTermUnit = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline Pipeline { get; set; } + + /// Private IPs of the resource + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Private IPs of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + public string[] PrivateIP { get => _resourceBody.PrivateIP?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.PrivateIP = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Storage Sku + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Storage Sku")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + public string StorageSku { get => _resourceBody.StorageSku ?? null; set => _resourceBody.StorageSku = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// User Email + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User Email")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmail { get => _resourceBody.UserDetailEmail ?? null; set => _resourceBody.UserDetailEmail = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzQumuloFileSystem_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.SetAzQumuloFileSystem_UpdateExpanded Clone() + { + var clone = new SetAzQumuloFileSystem_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParameters() + { + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity()); + } + } + // calculate IdentityType + if (this.UserAssignedIdentity?.Length > 0) + { + if ("SystemAssigned".Equals(_resourceBody.IdentityType, StringComparison.InvariantCultureIgnoreCase)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else + { + _resourceBody.IdentityType = "UserAssigned"; + } + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + this.PreProcessManagedIdentityParameters(); + await this.Client.FileSystemsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzQumuloFileSystem_UpdateExpanded() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonFilePath.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonFilePath.cs new file mode 100644 index 00000000000..ab37dd741d9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonFilePath.cs @@ -0,0 +1,606 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// update a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzQumuloFileSystem_UpdateViaJsonFilePath", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"update a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.NotSuggestDefaultParameterSet] + public partial class SetAzQumuloFileSystem_UpdateViaJsonFilePath : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + public global::System.String _jsonString; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonFilePath; + + /// Path of Json file supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Path of Json file supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Path of Json file supplied to the Update operation", + SerializedName = @"JsonFilePath", + PossibleTypes = new [] { typeof(string) })] + public string JsonFilePath { get => this._jsonFilePath; set { if (!System.IO.File.Exists(value)) { throw new Exception("Cannot find File " + value); } this._jsonString = System.IO.File.ReadAllText(value); this._jsonFilePath = value; } } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzQumuloFileSystem_UpdateViaJsonFilePath + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.SetAzQumuloFileSystem_UpdateViaJsonFilePath Clone() + { + var clone = new SetAzQumuloFileSystem_UpdateViaJsonFilePath(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonFilePath = this.JsonFilePath; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzQumuloFileSystem_UpdateViaJsonFilePath() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonString.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonString.cs new file mode 100644 index 00000000000..eb533c566cf --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/SetAzQumuloFileSystem_UpdateViaJsonString.cs @@ -0,0 +1,604 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// update a FileSystemResource + /// + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.InternalExport] + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Set, @"AzQumuloFileSystem_UpdateViaJsonString", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"update a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.HttpPath(Path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}", ApiVersion = "2024-06-19")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.NotSuggestDefaultParameterSet] + public partial class SetAzQumuloFileSystem_UpdateViaJsonString : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Accessor for our copy of the InvocationInfo. + public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } + + /// Backing field for property. + private string _jsonString; + + /// Json string supplied to the Update operation + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Json string supplied to the Update operation")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Json string supplied to the Update operation", + SerializedName = @"JsonString", + PossibleTypes = new [] { typeof(string) })] + public string JsonString { get => this._jsonString; set => this._jsonString = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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 Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of SetAzQumuloFileSystem_UpdateViaJsonString + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.SetAzQumuloFileSystem_UpdateViaJsonString Clone() + { + var clone = new SetAzQumuloFileSystem_UpdateViaJsonString(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone.SubscriptionId = this.SubscriptionId; + clone.ResourceGroupName = this.ResourceGroupName; + clone.Name = this.Name; + clone.JsonString = this.JsonString; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + await this.Client.FileSystemsCreateOrUpdateViaJsonString(SubscriptionId, ResourceGroupName, Name, _jsonString, onOk, onDefault, this, Pipeline); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public SetAzQumuloFileSystem_UpdateViaJsonString() + { + + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateExpanded.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateExpanded.cs new file mode 100644 index 00000000000..5d62f490e18 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateExpanded.cs @@ -0,0 +1,848 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// update a FileSystemResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzQumuloFileSystem_UpdateExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"update a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + public partial class UpdateAzQumuloFileSystem_UpdateExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Initial administrator password of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Initial administrator password of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + public string AdminPassword { get => _resourceBody.AdminPassword ?? null; set => _resourceBody.AdminPassword = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Availability zone + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Availability zone")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + public string AvailabilityZone { get => _resourceBody.AvailabilityZone ?? null; set => _resourceBody.AvailabilityZone = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// File system Id of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "File system Id of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + public string ClusterLoginUrl { get => _resourceBody.ClusterLoginUrl ?? null; set => _resourceBody.ClusterLoginUrl = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Delegated subnet id for Vnet injection + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Delegated subnet id for Vnet injection")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + public string DelegatedSubnetId { get => _resourceBody.DelegatedSubnetId ?? null; set => _resourceBody.DelegatedSubnetId = value; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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; } } + + /// Marketplace Subscription Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace Subscription Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailMarketplaceSubscriptionId { get => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId = value; } + + /// Offer Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailOfferId { get => _resourceBody.MarketplaceDetailOfferId ?? null; set => _resourceBody.MarketplaceDetailOfferId = value; } + + /// Plan Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPlanId { get => _resourceBody.MarketplaceDetailPlanId ?? null; set => _resourceBody.MarketplaceDetailPlanId = value; } + + /// Publisher Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPublisherId { get => _resourceBody.MarketplaceDetailPublisherId ?? null; set => _resourceBody.MarketplaceDetailPublisherId = value; } + + /// Term Unit + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Unit")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailTermUnit { get => _resourceBody.MarketplaceDetailTermUnit ?? null; set => _resourceBody.MarketplaceDetailTermUnit = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Token => _cancellationTokenSource.Token; + + /// Backing field for property. + private string _name; + + /// Name of the File System resource + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the File System resource")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"Name of the File System resource", + SerializedName = @"fileSystemName", + PossibleTypes = new [] { typeof(string) })] + [global::System.Management.Automation.Alias("FileSystemName")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline Pipeline { get; set; } + + /// Private IPs of the resource + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Private IPs of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + public string[] PrivateIP { get => _resourceBody.PrivateIP?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.PrivateIP = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } + + /// Storage Sku + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Storage Sku")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + public string StorageSku { get => _resourceBody.StorageSku ?? null; set => _resourceBody.StorageSku = value; } + + /// Backing field for property. + private string _subscriptionId; + + /// The ID of the target subscription. The value must be an UUID. + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription. The value must be an UUID.")] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = true, + ReadOnly = false, + Description = @"The ID of the target subscription. The value must be an UUID.", + SerializedName = @"subscriptionId", + PossibleTypes = new [] { typeof(string) })] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.DefaultInfo( + Name = @"", + Description =@"", + Script = @"(Get-AzContext).Subscription.Id", + SetCondition = @"")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// User Email + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User Email")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmail { get => _resourceBody.UserDetailEmail ?? null; set => _resourceBody.UserDetailEmail = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzQumuloFileSystem_UpdateExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.UpdateAzQumuloFileSystem_UpdateExpanded Clone() + { + var clone = new UpdateAzQumuloFileSystem_UpdateExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + 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() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParametersWithGetResult() + { + bool supportsSystemAssignedIdentity = (true == this.EnableSystemAssignedIdentity || null == this.EnableSystemAssignedIdentity && true == _resourceBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _resourceBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _resourceBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned"; + } + else + { + _resourceBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + _resourceBody = await this.Client.FileSystemsGetWithResult(SubscriptionId, ResourceGroupName, Name, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FileSystemsCreateOrUpdate(SubscriptionId, ResourceGroupName, Name, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate); + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzQumuloFileSystem_UpdateExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StorageSku"))) + { + this.StorageSku = (string)(this.MyInvocation?.BoundParameters["StorageSku"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DelegatedSubnetId"))) + { + this.DelegatedSubnetId = (string)(this.MyInvocation?.BoundParameters["DelegatedSubnetId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ClusterLoginUrl"))) + { + this.ClusterLoginUrl = (string)(this.MyInvocation?.BoundParameters["ClusterLoginUrl"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PrivateIP"))) + { + this.PrivateIP = (string[])(this.MyInvocation?.BoundParameters["PrivateIP"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AdminPassword"))) + { + this.AdminPassword = (string)(this.MyInvocation?.BoundParameters["AdminPassword"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AvailabilityZone"))) + { + this.AvailabilityZone = (string)(this.MyInvocation?.BoundParameters["AvailabilityZone"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailMarketplaceSubscriptionId"))) + { + this.MarketplaceDetailMarketplaceSubscriptionId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailMarketplaceSubscriptionId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailPlanId"))) + { + this.MarketplaceDetailPlanId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailPlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailOfferId"))) + { + this.MarketplaceDetailOfferId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailOfferId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailPublisherId"))) + { + this.MarketplaceDetailPublisherId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailPublisherId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailTermUnit"))) + { + this.MarketplaceDetailTermUnit = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailTermUnit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserDetailEmail"))) + { + this.UserDetailEmail = (string)(this.MyInvocation?.BoundParameters["UserDetailEmail"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded.cs new file mode 100644 index 00000000000..e0a40fe6197 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/cmdlets/UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded.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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Extensions; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets; + using System; + + /// update a FileSystemResource + /// + /// [OpenAPI] Get=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// [OpenAPI] CreateOrUpdate=>PUT:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Qumulo.Storage/fileSystems/{fileSystemName}" + /// + [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzQumuloFileSystem_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] + [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource))] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Description(@"update a FileSystemResource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Generated] + public partial class UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener, + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext + { + /// A unique id generatd for the this cmdlet when it is instantiated. + private string __correlationId = System.Guid.NewGuid().ToString(); + + /// A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet) + private global::System.Management.Automation.InvocationInfo __invocationInfo; + + /// A unique id generatd for the this cmdlet when ProcessRecord() is called. + private string __processRecordId; + + /// + /// The for this operation. + /// + private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); + + /// A dictionary to carry over additional data for pipeline. + private global::System.Collections.Generic.Dictionary _extensibleParameters = new System.Collections.Generic.Dictionary(); + + /// A buffer to record first returned object in response. + private object _firstResponse = null; + + /// + /// Concrete tracked resource types can be created by aliasing this type using a specific property type. + /// + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource _resourceBody = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.FileSystemResource(); + + /// + /// A flag to tell whether it is the first returned object in a call. Zero means no response yet. One means 1 returned object. + /// Two means multiple returned objects in response. + /// + private int _responseSize = 0; + + /// Initial administrator password of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Initial administrator password of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Initial administrator password of the resource", + SerializedName = @"adminPassword", + PossibleTypes = new [] { typeof(string) })] + public string AdminPassword { get => _resourceBody.AdminPassword ?? null; set => _resourceBody.AdminPassword = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter AsJob { get; set; } + + /// Availability zone + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Availability zone")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Availability zone", + SerializedName = @"availabilityZone", + PossibleTypes = new [] { typeof(string) })] + public string AvailabilityZone { get => _resourceBody.AvailabilityZone ?? null; set => _resourceBody.AvailabilityZone = 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter Break { get; set; } + + /// Accessor for cancellationTokenSource. + public global::System.Threading.CancellationTokenSource CancellationTokenSource { get => _cancellationTokenSource ; set { _cancellationTokenSource = value; } } + + /// The reference to the client API class. + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.ClientAPI; + + /// File system Id of the resource + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "File system Id of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"File system Id of the resource", + SerializedName = @"clusterLoginUrl", + PossibleTypes = new [] { typeof(string) })] + public string ClusterLoginUrl { get => _resourceBody.ClusterLoginUrl ?? null; set => _resourceBody.ClusterLoginUrl = value; } + + /// + /// The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet + /// against a different subscription + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.")] + [global::System.Management.Automation.ValidateNotNull] + [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Azure)] + public global::System.Management.Automation.PSObject DefaultProfile { get; set; } + + /// Delegated subnet id for Vnet injection + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Delegated subnet id for Vnet injection")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Delegated subnet id for Vnet injection", + SerializedName = @"delegatedSubnetId", + PossibleTypes = new [] { typeof(string) })] + public string DelegatedSubnetId { get => _resourceBody.DelegatedSubnetId ?? null; set => _resourceBody.DelegatedSubnetId = value; } + + /// Determines whether to enable a system-assigned identity for the resource. + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Determines whether to enable a system-assigned identity for the resource.")] + public System.Boolean? EnableSystemAssignedIdentity { get; set; } + + /// Accessor for extensibleParameters. + public global::System.Collections.Generic.IDictionary ExtensibleParameters { get => _extensibleParameters ; } + + /// SendAsync Pipeline Steps to be appended to the front of the pipeline + [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] + [global::System.Management.Automation.ValidateNotNull] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } + + /// Backing field for property. + private Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity _inputObject; + + /// Identity Parameter + [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Path)] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IQumuloIdentity 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; } } + + /// Marketplace Subscription Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Marketplace Subscription Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Marketplace Subscription Id", + SerializedName = @"marketplaceSubscriptionId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailMarketplaceSubscriptionId { get => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId ?? null; set => _resourceBody.MarketplaceDetailMarketplaceSubscriptionId = value; } + + /// Offer Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Offer Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Offer Id", + SerializedName = @"offerId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailOfferId { get => _resourceBody.MarketplaceDetailOfferId ?? null; set => _resourceBody.MarketplaceDetailOfferId = value; } + + /// Plan Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Plan Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Plan Id", + SerializedName = @"planId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPlanId { get => _resourceBody.MarketplaceDetailPlanId ?? null; set => _resourceBody.MarketplaceDetailPlanId = value; } + + /// Publisher Id + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Publisher Id")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Publisher Id", + SerializedName = @"publisherId", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailPublisherId { get => _resourceBody.MarketplaceDetailPublisherId ?? null; set => _resourceBody.MarketplaceDetailPublisherId = value; } + + /// Term Unit + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Term Unit")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Term Unit", + SerializedName = @"termUnit", + PossibleTypes = new [] { typeof(string) })] + public string MarketplaceDetailTermUnit { get => _resourceBody.MarketplaceDetailTermUnit ?? null; set => _resourceBody.MarketplaceDetailTermUnit = value; } + + /// + /// cancellation delegate. Stops the cmdlet when called. + /// + global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; + + /// cancellation token. + global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter NoWait { get; set; } + + /// + /// The instance of the that the remote call will use. + /// + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.HttpPipeline Pipeline { get; set; } + + /// Private IPs of the resource + [global::System.Management.Automation.AllowEmptyCollection] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Private IPs of the resource")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Private IPs of the resource", + SerializedName = @"privateIPs", + PossibleTypes = new [] { typeof(string) })] + public string[] PrivateIP { get => _resourceBody.PrivateIP?.ToArray() ?? null /* fixedArrayOf */; set => _resourceBody.PrivateIP = (value != null ? new System.Collections.Generic.List(value) : null); } + + /// 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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Runtime)] + public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } + + /// Storage Sku + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Storage Sku")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Storage Sku", + SerializedName = @"storageSku", + PossibleTypes = new [] { typeof(string) })] + public string StorageSku { get => _resourceBody.StorageSku ?? null; set => _resourceBody.StorageSku = value; } + + /// Resource tags. + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ExportAs(typeof(global::System.Collections.Hashtable))] + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource tags.")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"Resource tags.", + SerializedName = @"tags", + PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags) })] + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags Tag { get => _resourceBody.Tag ?? null /* object */; set => _resourceBody.Tag = value; } + + /// + /// The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in + /// the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.' + /// + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The array of user assigned identities associated with the resource. The elements in array will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}.'")] + [global::System.Management.Automation.AllowEmptyCollection] + public string[] UserAssignedIdentity { get; set; } + + /// User Email + [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "User Email")] + [global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Qumulo.ParameterCategory.Body)] + [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Info( + Required = false, + ReadOnly = false, + Description = @"User Email", + SerializedName = @"email", + PossibleTypes = new [] { typeof(string) })] + public string UserDetailEmail { get => _resourceBody.UserDetailEmail ?? null; set => _resourceBody.UserDetailEmail = value; } + + /// + /// overrideOnDefault will be called before the regular onDefault has been processed, allowing customization of what + /// happens on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// /// Determines if the rest of the onDefault method should be processed, or if the method should + /// return immediately (set to true to skip further processing ) + + partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// overrideOnOk will be called before the regular onOk has been processed, allowing customization of what happens + /// on that response. Implement this method in a partial class to enable this behavior + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// from the remote call + /// /// Determines if the rest of the onOk method should be processed, or if the method should return + /// immediately (set to true to skip further processing ) + + partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response, ref global::System.Threading.Tasks.Task returnNow); + + /// + /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) + /// + protected override void BeginProcessing() + { + var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryId.Invoke(); + if (telemetryId != "" && telemetryId != "internal") + { + __correlationId = telemetryId; + } + Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); + if (Break) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.AttachDebugger.Break(); + } + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + + /// Creates a duplicate instance of this cmdlet (via JSON serialization). + /// a duplicate instance of UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Cmdlets.UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded Clone() + { + var clone = new UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded(); + clone.__correlationId = this.__correlationId; + clone.__processRecordId = this.__processRecordId; + clone.DefaultProfile = this.DefaultProfile; + clone.InvocationInformation = this.InvocationInformation; + clone.Proxy = this.Proxy; + clone.Pipeline = this.Pipeline; + clone.AsJob = this.AsJob; + clone.Break = this.Break; + clone.ProxyCredential = this.ProxyCredential; + clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; + clone.HttpPipelinePrepend = this.HttpPipelinePrepend; + clone.HttpPipelineAppend = this.HttpPipelineAppend; + clone._resourceBody = this._resourceBody; + return clone; + } + + /// Performs clean-up after the command execution + protected override void EndProcessing() + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse); + } + var telemetryInfo = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.GetTelemetryInfo?.Invoke(__correlationId); + if (telemetryInfo != null) + { + telemetryInfo.TryGetValue("ShowSecretsWarning", out var showSecretsWarning); + telemetryInfo.TryGetValue("SanitizedProperties", out var sanitizedProperties); + telemetryInfo.TryGetValue("InvocationName", out var invocationName); + if (showSecretsWarning == "true") + { + if (string.IsNullOrEmpty(sanitizedProperties)) + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing secrets. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + else + { + WriteWarning($"The output of cmdlet {invocationName} may compromise security by showing the following secrets: {sanitizedProperties}. Learn more at https://go.microsoft.com/fwlink/?linkid=2258844"); + } + } + } + } + + /// Handles/Dispatches events during the call to the REST service. + /// The message id + /// The message cancellation token. When this call is cancelled, this should be true + /// Detailed message data for the message event. + /// + /// A that will be complete when handling of the message is completed. + /// + async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Verbose: + { + WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.Warning: + { + WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Debug: + { + WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.Progress: + { + var data = messageData(); + int progress = (int)data.Value; + string activityMessage, statusDescription; + global::System.Management.Automation.ProgressRecordType recordType; + if (progress < 100) + { + activityMessage = "In progress"; + statusDescription = "Checking operation status"; + recordType = System.Management.Automation.ProgressRecordType.Processing; + } + else + { + activityMessage = "Completed"; + statusDescription = "Completed"; + recordType = System.Management.Automation.ProgressRecordType.Completed; + } + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, activityMessage, statusDescription) + { + PercentComplete = progress, + RecordType = recordType + }); + return ; + } + case Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.DelayBeforePolling: + { + var data = messageData(); + if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) + { + 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.Qumulo.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); + // do nothing more. + data.Cancel(); + return; + } + } + else + { + if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) + { + int delay = (int)(response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); + WriteDebug($"Delaying {delay} seconds before polling."); + for (var now = 0; now < delay; ++now) + { + WriteProgress(new global::System.Management.Automation.ProgressRecord(1, "In progress", "Checking operation status") + { + PercentComplete = now * 100 / delay + }); + await global::System.Threading.Tasks.Task.Delay(1000, token); + } + } + } + break; + } + } + await Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.Signal(id, token, messageData, (i, t, m) => ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(i, t, () => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventDataConverter.ConvertFrom(m()) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.EventData), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); + if (token.IsCancellationRequested) + { + return ; + } + WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); + } + } + + private void PreProcessManagedIdentityParametersWithGetResult() + { + bool supportsSystemAssignedIdentity = (true == this.EnableSystemAssignedIdentity || null == this.EnableSystemAssignedIdentity && true == _resourceBody?.IdentityType?.Contains("SystemAssigned")); + bool supportsUserAssignedIdentity = false; + if (this.UserAssignedIdentity?.Length > 0) + { + // calculate UserAssignedIdentity + _resourceBody.IdentityUserAssignedIdentity.Clear(); + foreach( var id in this.UserAssignedIdentity ) + { + _resourceBody.IdentityUserAssignedIdentity.Add(id, new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.UserAssignedIdentity()); + } + } + supportsUserAssignedIdentity = true == this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && this.UserAssignedIdentity?.Length > 0 || + true != this.MyInvocation?.BoundParameters?.ContainsKey("UserAssignedIdentity") && true == _resourceBody.IdentityType?.Contains("UserAssigned"); + if (!supportsUserAssignedIdentity) + { + _resourceBody.IdentityUserAssignedIdentity = null; + } + // calculate IdentityType + if ((supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned,UserAssigned"; + } + else if ((supportsUserAssignedIdentity && !supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "UserAssigned"; + } + else if ((!supportsUserAssignedIdentity && supportsSystemAssignedIdentity)) + { + _resourceBody.IdentityType = "SystemAssigned"; + } + else + { + _resourceBody.IdentityType = "None"; + } + } + + /// Performs execution of the command. + protected override void ProcessRecord() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + __processRecordId = System.Guid.NewGuid().ToString(); + try + { + // work + if (ShouldProcess($"Call remote 'FileSystemsCreateOrUpdate' operation")) + { + if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) + { + var instance = this.Clone(); + var job = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token) ) + { + asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName, this.ExtensibleParameters); + if (null != HttpPipelinePrepend) + { + Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); + } + if (null != HttpPipelineAppend) + { + Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); + } + // get the client instance + try + { + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + if (InputObject?.Id != null) + { + _resourceBody = await this.Client.FileSystemsGetViaIdentityWithResult(InputObject.Id, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FileSystemsCreateOrUpdateViaIdentity(InputObject.Id, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate); + } + 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.FileSystemName) + { + ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.FileSystemName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); + } + _resourceBody = await this.Client.FileSystemsGetWithResult(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FileSystemName ?? null, this, Pipeline); + this.PreProcessManagedIdentityParametersWithGetResult(); + this.Update_resourceBody(); + await this.Client.FileSystemsCreateOrUpdate(InputObject.SubscriptionId ?? null, InputObject.ResourceGroupName ?? null, InputObject.FileSystemName ?? null, _resourceBody, onOk, onDefault, this, Pipeline, Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeCreate|Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SerializationMode.IncludeUpdate); + } + await ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } + } + catch (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Events.CmdletProcessRecordAsyncEnd); + } + } + } + + /// Interrupts currently running code within the command. + protected override void StopProcessing() + { + ((Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IEventListener)this).Cancel(); + base.StopProcessing(); + } + + /// + /// Initializes a new instance of the cmdlet class. + /// + public UpdateAzQumuloFileSystem_UpdateViaIdentityExpanded() + { + + } + + private void Update_resourceBody() + { + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("Tag"))) + { + this.Tag = (Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.ITags)(this.MyInvocation?.BoundParameters["Tag"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("StorageSku"))) + { + this.StorageSku = (string)(this.MyInvocation?.BoundParameters["StorageSku"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("DelegatedSubnetId"))) + { + this.DelegatedSubnetId = (string)(this.MyInvocation?.BoundParameters["DelegatedSubnetId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("ClusterLoginUrl"))) + { + this.ClusterLoginUrl = (string)(this.MyInvocation?.BoundParameters["ClusterLoginUrl"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("PrivateIP"))) + { + this.PrivateIP = (string[])(this.MyInvocation?.BoundParameters["PrivateIP"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AdminPassword"))) + { + this.AdminPassword = (string)(this.MyInvocation?.BoundParameters["AdminPassword"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("AvailabilityZone"))) + { + this.AvailabilityZone = (string)(this.MyInvocation?.BoundParameters["AvailabilityZone"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailMarketplaceSubscriptionId"))) + { + this.MarketplaceDetailMarketplaceSubscriptionId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailMarketplaceSubscriptionId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailPlanId"))) + { + this.MarketplaceDetailPlanId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailPlanId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailOfferId"))) + { + this.MarketplaceDetailOfferId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailOfferId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailPublisherId"))) + { + this.MarketplaceDetailPublisherId = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailPublisherId"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("MarketplaceDetailTermUnit"))) + { + this.MarketplaceDetailTermUnit = (string)(this.MyInvocation?.BoundParameters["MarketplaceDetailTermUnit"]); + } + if ((bool)(true == this.MyInvocation?.BoundParameters.ContainsKey("UserDetailEmail"))) + { + this.UserDetailEmail = (string)(this.MyInvocation?.BoundParameters["UserDetailEmail"]); + } + } + + /// + new protected void WriteObject(object sendToPipeline) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline); + } + + /// + /// + new protected void WriteObject(object sendToPipeline, bool enumerateCollection) + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Module.Instance.SanitizeOutput?.Invoke(sendToPipeline, __correlationId); + base.WriteObject(sendToPipeline, enumerateCollection); + } + + /// + /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). + /// + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IErrorResponse + /// from the remote call + /// + /// A that will be complete when handling of the method is completed. + /// + private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task response) + { + using( NoSynchronizationContext ) + { + var _returnNow = global::System.Threading.Tasks.Task.FromResult(false); + overrideOnDefault(responseMessage, response, ref _returnNow); + // if overrideOnDefault has returned true, then return right away. + if ((null != _returnNow && await _returnNow)) + { + return ; + } + // Error Response : default + var code = (await response)?.Code; + var message = (await response)?.Message; + if ((null == code || null == message)) + { + // Unrecognized Response. Create an error record based on what we have. + var ex = new Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.RestException(responseMessage, await response); + WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } + }); + } + else + { + WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { }) + { + ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } + }); + } + } + } + + /// a delegate that is called when the remote service returns 200 (OK). + /// the raw response message as an global::System.Net.Http.HttpResponseMessage. + /// the body result as a Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Models.IFileSystemResource + /// 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.Qumulo.Models.IFileSystemResource + var result = (await response); + if (null != result) + { + if (0 == _responseSize) + { + _firstResponse = result; + _responseSize = 1; + } + else + { + if (1 ==_responseSize) + { + // Flush buffer + WriteObject(_firstResponse.AddMultipleTypeNameIntoPSObject()); + } + WriteObject(result.AddMultipleTypeNameIntoPSObject()); + _responseSize = 2; + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncCommandRuntime.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncCommandRuntime.cs new file mode 100644 index 00000000000..aae56c6f70a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncCommandRuntime.cs @@ -0,0 +1,832 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + using System.Management.Automation; + using System.Management.Automation.Host; + using System.Threading; + using System.Linq; + + internal interface IAsyncCommandRuntimeExtensions + { + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep func); + System.Collections.Generic.IEnumerable Wrap(System.Collections.Generic.IEnumerable funcs); + + T ExecuteSync(System.Func step); + } + + public class AsyncCommandRuntime : System.Management.Automation.ICommandRuntime2, IAsyncCommandRuntimeExtensions, System.IDisposable + { + private ICommandRuntime2 originalCommandRuntime; + private System.Threading.Thread originalThread; + public bool AllowInteractive { get; set; } = false; + + public CancellationToken cancellationToken; + SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); + ManualResetEventSlim readyToRun = new ManualResetEventSlim(false); + ManualResetEventSlim completed = new ManualResetEventSlim(false); + + System.Action runOnMainThread; + + private System.Management.Automation.PSCmdlet cmdlet; + + internal AsyncCommandRuntime(System.Management.Automation.PSCmdlet cmdlet, CancellationToken cancellationToken) + { + this.originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + this.originalThread = System.Threading.Thread.CurrentThread; + this.cancellationToken = cancellationToken; + this.cmdlet = cmdlet; + if (cmdlet.PagingParameters != null) + { + WriteDebug("Client side pagination is enabled for this cmdlet"); + } + cmdlet.CommandRuntime = this; + } + + public PSHost Host => this.originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => this.originalCommandRuntime.CurrentPSTransaction; + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new System.Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + private void WaitOurTurn() + { + // wait for our turn to play + semaphore?.Wait(cancellationToken); + + // ensure that completed is not set + completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, completed?.WaitHandle }); + + // let go of the semaphore + semaphore?.Release(); + + } + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool yta = yesToAll; + bool nta = noToAll; + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + ShouldProcessReason reason = ShouldProcessReason.None; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, out reason); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + return originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + bool result = false; + + // set the function to run + runOnMainThread = () => result = originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (this.originalThread == System.Threading.Thread.CurrentThread) + { + originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + runOnMainThread = () => originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + return; + } + catch (System.OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Wait(System.Threading.Tasks.Task ProcessRecordAsyncTask, System.Threading.CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] { readyToRun.WaitHandle, ((System.IAsyncResult)ProcessRecordAsyncTask).AsyncWaitHandle }); + if (readyToRun.IsSet) + { + // reset the request for the next time + readyToRun.Reset(); + + // run the delegate on this thread + runOnMainThread(); + + // tell the originator everything is complete + completed.Set(); + } + } + while (!ProcessRecordAsyncTask.IsCompleted); + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + public Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.SendAsyncStep Wrap(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncJob.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncJob.cs new file mode 100644 index 00000000000..79cb1d9907d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncOperationResponse.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncOperationResponse.cs new file mode 100644 index 00000000000..ec910058caf --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/AsyncOperationResponse.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Json.JsonNode node) + { + return node is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode.Parse(jsonText)); + + } + + public partial class AsyncOperationResponseTypeConverter : System.Management.Automation.PSTypeConverter + { + + /// + /// Determines if the converter can convert the parameter to the + /// parameter. + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false. + /// + public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); + + /// + /// Determines if the converter can convert the parameter to a type + /// parameter. + /// + /// the instance to check if it can be converted to the type. + /// + /// true if the instance could be converted to a type, otherwise false + /// + public static bool CanConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return true; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + // we say yest to PSObjects + return true; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + // we say yest to Hashtables/dictionaries + return true; + } + try + { + if (null != sourceValue.ToJsonString()) + { + return true; + } + } + catch + { + // Not one of our objects + } + try + { + string text = sourceValue.ToString()?.Trim(); + return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonType.Object; + } + catch + { + // Doesn't look like it can be treated as JSON + } + return false; + } + + /// + /// Determines if the parameter can be converted to the parameter + /// + /// the to convert from + /// the to convert to + /// + /// true if the converter can convert the parameter to the + /// parameter, otherwise false + /// + public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; + + /// + /// Converts the parameter to the parameter using and + /// + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// + /// an instance of , or null if there is no suitable conversion. + /// + public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Converts the parameter into an instance of + /// + /// the value to convert into an instance of . + /// + /// an instance of , or null if there is no suitable conversion. + /// + public static object ConvertFrom(dynamic sourceValue) + { + if (null == sourceValue) + { + return null; + } + global::System.Type type = sourceValue.GetType(); + if (typeof(AsyncOperationResponse).IsAssignableFrom(type)) + { + return sourceValue; + } + try + { + return AsyncOperationResponse.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString()); ; + } + catch + { + // Unable to use JSON pattern + } + + if (typeof(System.Management.Automation.PSObject).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as System.Management.Automation.PSObject).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) + { + return new AsyncOperationResponse { Target = (sourceValue as global::System.Collections.IDictionary).GetValueForProperty("target", "", global::System.Convert.ToString) }; + } + return null; + } + + /// NotImplemented -- this will return null + /// the to convert from + /// the to convert to + /// not used by this TypeConverter. + /// when set to true, will ignore the case when converting. + /// will always return null. + public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs new file mode 100644 index 00000000000..67790468215 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/ExternalDocsAttribute.cs @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo +{ + using System; + using System.Collections.Generic; + using System.Text; + + [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] + public class ExternalDocsAttribute : Attribute + { + + public string Description { get; } + + public string Url { get; } + + public ExternalDocsAttribute(string url) + { + Url = url; + } + + public ExternalDocsAttribute(string url, string description) + { + Url = url; + Description = description; + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs new file mode 100644 index 00000000000..8f30a45d8dc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Attributes/PSArgumentCompleterAttribute.cs @@ -0,0 +1,52 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo +{ + public class PSArgumentCompleterAttribute : ArgumentCompleterAttribute + { + internal string[] ResourceTypes; + + public PSArgumentCompleterAttribute(params string[] argumentList) : base(CreateScriptBlock(argumentList)) + { + ResourceTypes = argumentList; + } + + public static ScriptBlock CreateScriptBlock(string[] resourceTypes) + { + List outputResourceTypes = new List(); + foreach (string resourceType in resourceTypes) + { + if (resourceType.Contains(" ")) + { + outputResourceTypes.Add("\'\'" + resourceType + "\'\'"); + } + else + { + outputResourceTypes.Add(resourceType); + } + } + string scriptResourceTypeList = "'" + String.Join("' , '", outputResourceTypes) + "'"; + string script = "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)\n" + + String.Format("$values = {0}\n", scriptResourceTypeList) + + "$values | Where-Object { $_ -Like \"$wordToComplete*\" -or $_ -Like \"'$wordToComplete*\" } | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }"; + ScriptBlock scriptBlock = ScriptBlock.Create(script); + return scriptBlock; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportCmdletSurface.cs new file mode 100644 index 00000000000..3d7d730d60b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportExampleStub.cs new file mode 100644 index 00000000000..14efb4b8c99 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs new file mode 100644 index 00000000000..144c500cf74 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportFormatPs1xml.cs @@ -0,0 +1,103 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + private const string PropertiesExcludedForTableview = @"Id,Type"; + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + private static string SelectedBySuffix = @"#Multiple"; + + protected override void ProcessRecord() + { + try + { + var viewModels = GetFilteredViewParameters().Select(CreateViewModel).ToList(); + var ps1xml = new Configuration + { + ViewDefinitions = new ViewDefinitions + { + Views = viewModels + } + }; + File.WriteAllText(FilePath, ps1xml.ToXmlString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static IEnumerable GetFilteredViewParameters() + { + //https://stackoverflow.com/a/79738/294804 + //https://stackoverflow.com/a/949285/294804 + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass + && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace)) + && !t.GetCustomAttributes().Any()); + return types.Select(t => new ViewParameters(t, t.GetProperties() + .Select(p => new PropertyFormat(p)) + .Where(pf => !pf.Property.GetCustomAttributes().Any() + && (!PropertiesExcludedForTableview.Split(',').Contains(pf.Property.Name)) + && (pf.FormatTable != null || (pf.Origin != PropertyOrigin.Inlined && pf.Property.PropertyType.IsPsSimple()))) + .OrderByDescending(pf => pf.Index.HasValue) + .ThenBy(pf => pf.Index) + .ThenByDescending(pf => pf.Origin.HasValue) + .ThenBy(pf => pf.Origin))).Where(vp => vp.Properties.Any()); + } + + private static View CreateViewModel(ViewParameters viewParameters) + { + var entries = viewParameters.Properties.Select(pf => + (TableColumnHeader: new TableColumnHeader { Label = pf.Label, Width = pf.Width }, + TableColumnItem: new TableColumnItem { PropertyName = pf.Property.Name })).ToArray(); + + return new View + { + Name = viewParameters.Type.FullName, + ViewSelectedBy = new ViewSelectedBy + { + TypeName = string.Concat(viewParameters.Type.FullName, SelectedBySuffix) + }, + TableControl = new TableControl + { + TableHeaders = new TableHeaders + { + TableColumnHeaders = entries.Select(e => e.TableColumnHeader).ToList() + }, + TableRowEntries = new TableRowEntries + { + TableRowEntry = new TableRowEntry + { + TableColumnItems = new TableColumnItems + { + TableItems = entries.Select(e => e.TableColumnItem).ToList() + } + } + } + } + }; + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs new file mode 100644 index 00000000000..a4f733a3394 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportHelpMarkdown.cs @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.MarkdownRenderer; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "HelpMarkdown")] + [DoNotExport] + public class ExportHelpMarkdown : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSModuleInfo ModuleInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] FunctionInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public PSObject[] HelpInfo { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter()] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var helpInfos = HelpInfo.Select(hi => hi.ToPsHelpInfo()); + var variantGroups = FunctionInfo.Select(fi => fi.BaseObject).Cast() + .Join(helpInfos, fi => fi.Name, phi => phi.CmdletName, (fi, phi) => fi.ToVariants(phi)) + .Select(va => new VariantGroup(ModuleInfo.Name, va.First().CmdletName, va, String.Empty)); + WriteMarkdowns(variantGroups, ModuleInfo.ToModuleInfo(), DocsFolder, ExamplesFolder, AddComplexInterfaceInfo.IsPresent); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportModelSurface.cs new file mode 100644 index 00000000000..aa579b207b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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.Qumulo.Models"; + private const string SupportNamespace = @"${$project.supportNamespace.fullName}"; + + protected override void ProcessRecord() + { + try + { + var types = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && (t.Namespace.StartsWith(ModelNamespace) || t.Namespace.StartsWith(SupportNamespace))); + var typeInfos = types.Select(t => new ModelTypeInfo + { + Type = t, + TypeName = t.Name, + Properties = t.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.GetIndexParameters().Any()).OrderBy(p => p.Name).ToArray(), + NamespaceGroup = t.Namespace.Split('.').LastOrDefault().EmptyIfNull() + }).Where(mti => mti.Properties.Any()); + var sb = UseExpandedFormat ? ExpandedFormat(typeInfos) : CondensedFormat(typeInfos); + Directory.CreateDirectory(OutputFolder); + File.WriteAllText(Path.Combine(OutputFolder, "ModelSurface.md"), sb.ToString()); + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + + private static StringBuilder ExpandedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + foreach (var typeInfo in typeInfos.OrderBy(mti => mti.TypeName).ThenBy(mti => mti.NamespaceGroup)) + { + sb.Append($"### {typeInfo.TypeName} [{typeInfo.NamespaceGroup}]{Environment.NewLine}"); + foreach (var property in typeInfo.Properties) + { + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}`{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + private static StringBuilder CondensedFormat(IEnumerable typeInfos) + { + var sb = new StringBuilder(); + var typeGroups = typeInfos + .GroupBy(mti => mti.TypeName) + .Select(tig => ( + Types: tig.Select(mti => mti.Type).ToArray(), + TypeName: tig.Key, + Properties: tig.SelectMany(mti => mti.Properties).DistinctBy(p => p.Name).OrderBy(p => p.Name).ToArray(), + NamespaceGroups: tig.Select(mti => mti.NamespaceGroup).OrderBy(ng => ng).ToArray() + )) + .OrderBy(tg => tg.TypeName); + foreach (var typeGroup in typeGroups) + { + var aType = typeGroup.Types.Select(GetAssociativeType).FirstOrDefault(t => t != null); + var aText = aType != null ? $@" \<{aType.ToSyntaxTypeName()}\>" : String.Empty; + sb.Append($"### {typeGroup.TypeName}{aText} [{String.Join(", ", typeGroup.NamespaceGroups)}]{Environment.NewLine}"); + foreach (var property in typeGroup.Properties) + { + var propertyAType = GetAssociativeType(property.PropertyType); + var propertyAText = propertyAType != null ? $" <{propertyAType.ToSyntaxTypeName()}>" : String.Empty; + var enumNames = GetEnumFieldNames(property.PropertyType.Unwrap()); + var enumNamesText = enumNames.Any() ? $" **{{{String.Join(", ", enumNames)}}}**" : String.Empty; + sb.Append($" - {property.Name} `{property.PropertyType.ToSyntaxTypeName()}{propertyAText}`{enumNamesText}{Environment.NewLine}"); + } + sb.AppendLine(); + } + + return sb; + } + + //https://stackoverflow.com/a/4963190/294804 + private static Type GetAssociativeType(Type type) => + type.GetInterfaces().FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>))?.GetGenericArguments().First(); + + private static string[] GetEnumFieldNames(Type type) => + type.IsValueType && !type.IsPrimitive && type != typeof(decimal) && type != typeof(DateTime) + ? type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == type).Select(p => p.Name).ToArray() + : new string[] { }; + + private class ModelTypeInfo + { + public Type Type { get; set; } + public string TypeName { get; set; } + public PropertyInfo[] Properties { get; set; } + public string NamespaceGroup { get; set; } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs new file mode 100644 index 00000000000..7428cabb6e9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportProxyCmdlet.cs @@ -0,0 +1,180 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpers; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.MarkdownRenderer; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyTypeExtensions; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "ProxyCmdlet", DefaultParameterSetName = "Docs")] + [DoNotExport] + public class ExportProxyCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string[] ModulePath { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string InternalFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [AllowEmptyString] + public string ModuleDescription { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + [ValidateNotNullOrEmpty] + public string DocsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExamplesFolder { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "Docs")] + public Guid ModuleGuid { get; set; } + + [Parameter(Mandatory = true, ParameterSetName = "NoDocs")] + public SwitchParameter ExcludeDocs { get; set; } + + [Parameter(ParameterSetName = "Docs")] + public SwitchParameter AddComplexInterfaceInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var variants = GetModuleCmdletsAndHelpInfo(this, ModulePath).SelectMany(ci => ci.ToVariants()).Where(v => !v.IsDoNotExport).ToArray(); + var allProfiles = variants.SelectMany(v => v.Profiles).Distinct().ToArray(); + var profileGroups = allProfiles.Any() + ? variants + .SelectMany(v => (v.Profiles.Any() ? v.Profiles : allProfiles).Select(p => (profile: p, variant: v))) + .GroupBy(pv => pv.profile) + .Select(pvg => new ProfileGroup(pvg.Select(pv => pv.variant).ToArray(), pvg.Key)) + : new[] { new ProfileGroup(variants) }; + var variantGroups = profileGroups.SelectMany(pg => pg.Variants + .GroupBy(v => new { v.CmdletName, v.IsInternal }) + .Select(vg => new VariantGroup(ModuleName, vg.Key.CmdletName, vg.Select(v => v).ToArray(), + Path.Combine(vg.Key.IsInternal ? InternalFolder : ExportsFolder, pg.ProfileFolder), pg.ProfileName, isInternal: vg.Key.IsInternal))) + .ToArray(); + var license = new StringBuilder(); + license.Append(@" +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +"); + HashSet LicenseSet = new HashSet(); + foreach (var variantGroup in variantGroups) + { + var parameterGroups = variantGroup.ParameterGroups.ToList(); + var isValidProfile = !String.IsNullOrEmpty(variantGroup.ProfileName) && variantGroup.ProfileName != NoProfiles; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, variantGroup.ProfileName) : ExamplesFolder; + var markdownInfo = new MarkdownHelpInfo(variantGroup, examplesFolder); + List examples = new List(); + foreach (var it in markdownInfo.Examples) + { + examples.Add(it); + } + variantGroup.HelpInfo.Examples = examples.ToArray(); + var sb = new StringBuilder(); + sb.Append($"{Environment.NewLine}"); + sb.Append(variantGroup.ToHelpCommentOutput()); + sb.Append($"function {variantGroup.CmdletName} {{{Environment.NewLine}"); + sb.Append(variantGroup.Aliases.ToAliasOutput()); + sb.Append(variantGroup.OutputTypes.ToOutputTypeOutput()); + sb.Append(variantGroup.ToCmdletBindingOutput()); + sb.Append(variantGroup.ProfileName.ToProfileOutput()); + + sb.Append("param("); + sb.Append($"{(parameterGroups.Any() ? Environment.NewLine : String.Empty)}"); + + foreach (var parameterGroup in parameterGroups) + { + var parameters = parameterGroup.HasAllVariants ? parameterGroup.Parameters.Take(1) : parameterGroup.Parameters; + parameters = parameters.Where(p => !p.IsHidden()); + if (!parameters.Any()) + { + continue; + } + foreach (var parameter in parameters) + { + sb.Append(parameter.ToParameterOutput(variantGroup.HasMultipleVariants, parameterGroup.HasAllVariants)); + } + sb.Append(parameterGroup.Aliases.ToAliasOutput(true)); + sb.Append(parameterGroup.HasValidateNotNull.ToValidateNotNullOutput()); + sb.Append(parameterGroup.HasAllowEmptyArray.ToAllowEmptyArray()); + sb.Append(parameterGroup.CompleterInfo.ToArgumentCompleterOutput()); + sb.Append(parameterGroup.OrderCategory.ToParameterCategoryOutput()); + sb.Append(parameterGroup.InfoAttribute.ToInfoOutput(parameterGroup.ParameterType)); + sb.Append(parameterGroup.ToDefaultInfoOutput()); + sb.Append(parameterGroup.ParameterType.ToParameterTypeOutput()); + sb.Append(parameterGroup.Description.ToParameterDescriptionOutput()); + sb.Append(parameterGroup.ParameterName.ToParameterNameOutput(parameterGroups.IndexOf(parameterGroup) == parameterGroups.Count - 1)); + } + sb.Append($"){Environment.NewLine}{Environment.NewLine}"); + + sb.Append(variantGroup.ToBeginOutput()); + sb.Append(variantGroup.ToProcessOutput()); + sb.Append(variantGroup.ToEndOutput()); + + sb.Append($"}}{Environment.NewLine}"); + + Directory.CreateDirectory(variantGroup.OutputFolder); + File.WriteAllText(variantGroup.FilePath, license.ToString()); + File.AppendAllText(variantGroup.FilePath, sb.ToString()); + if (!LicenseSet.Contains(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"))) + { + // only add license in the header + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), license.ToString()); + LicenseSet.Add(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1")); + } + File.AppendAllText(Path.Combine(variantGroup.OutputFolder, "ProxyCmdletDefinitions.ps1"), sb.ToString()); + } + + if (!ExcludeDocs) + { + var moduleInfo = new PsModuleHelpInfo(ModuleName, ModuleGuid, ModuleDescription); + foreach (var variantGroupsByProfile in variantGroups.GroupBy(vg => vg.ProfileName)) + { + var profileName = variantGroupsByProfile.Key; + var isValidProfile = !String.IsNullOrEmpty(profileName) && profileName != NoProfiles; + var docsFolder = isValidProfile ? Path.Combine(DocsFolder, profileName) : DocsFolder; + var examplesFolder = isValidProfile ? Path.Combine(ExamplesFolder, profileName) : ExamplesFolder; + WriteMarkdowns(variantGroupsByProfile, moduleInfo, docsFolder, examplesFolder, AddComplexInterfaceInfo.IsPresent); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs new file mode 100644 index 00000000000..217c88b695e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportPsd1.cs @@ -0,0 +1,193 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "Psd1")] + [DoNotExport] + public class ExportPsd1 : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string CustomFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string Psd1Path { get; set; } + + [Parameter(Mandatory = true)] + public Guid ModuleGuid { get; set; } + + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + private const string CustomFolderRelative = "./custom"; + private const string Indent = Psd1Indent; + private const string Undefined = "undefined"; + private bool IsUndefined(string value) => string.Equals(Undefined, value, StringComparison.OrdinalIgnoreCase); + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + if (!Directory.Exists(CustomFolder)) + { + throw new ArgumentException($"Custom folder '{CustomFolder}' does not exist"); + } + + string version = Convert.ToString(@"0.1.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.Qumulo.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: Qumulo cmdlets"}'"); + sb.AppendLine($@"{Indent}PowerShellVersion = '5.1'"); + sb.AppendLine($@"{Indent}DotNetFrameworkVersion = '4.7.2'"); + + // RequiredModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredModules = @({"undefined"})"); + } + + // RequiredAssemblies + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}RequiredAssemblies = @({"undefined"})"); + } + else + { + sb.AppendLine($@"{Indent}RequiredAssemblies = '{"./bin/Az.Qumulo.private.dll"}'"); + } + + // NestedModules + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}NestedModules = @({"undefined"})"); + } + + // FormatsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FormatsToProcess = @({"undefined"})"); + } + else + { + var customFormatPs1xmlFiles = Directory.GetFiles(CustomFolder) + .Where(f => f.EndsWith(".format.ps1xml")) + .Select(f => $"{CustomFolderRelative}/{Path.GetFileName(f)}"); + var formatList = customFormatPs1xmlFiles.Prepend("./Az.Qumulo.format.ps1xml").ToPsList(); + sb.AppendLine($@"{Indent}FormatsToProcess = {formatList}"); + } + + // TypesToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}TypesToProcess = @({"undefined"})"); + } + + // ScriptsToProcess + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}ScriptsToProcess = @({"undefined"})"); + } + + var functionInfos = GetScriptCmdlets(ExportsFolder).ToArray(); + // FunctionsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}FunctionsToExport = @({"undefined"})"); + } + else + { + var cmdletsList = functionInfos.Select(fi => fi.Name).Distinct().ToPsList(); + sb.AppendLine($@"{Indent}FunctionsToExport = {cmdletsList}"); + } + + // AliasesToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}AliasesToExport = @({"undefined"})"); + } + else + { + var aliasesList = functionInfos.SelectMany(fi => fi.ScriptBlock.Attributes).ToAliasNames().ToPsList(); + if (!String.IsNullOrEmpty(aliasesList)) { + sb.AppendLine($@"{Indent}AliasesToExport = {aliasesList}"); + } + } + + // CmdletsToExport + if (!IsUndefined("undefined")) + { + sb.AppendLine($@"{Indent}CmdletsToExport = @({"undefined"})"); + } + + sb.AppendLine($@"{Indent}PrivateData = @{{"); + sb.AppendLine($@"{Indent}{Indent}PSData = @{{"); + + if (previewVersion != null) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}Prerelease = '{previewVersion}'"); + } + sb.AppendLine($@"{Indent}{Indent}{Indent}Tags = {"Azure ResourceManager ARM PSModule Sphere".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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs new file mode 100644 index 00000000000..86638f30c4f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/ExportTestStub.cs @@ -0,0 +1,197 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + [Cmdlet(VerbsData.Export, "TestStub")] + [DoNotExport] + public class ExportTestStub : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ModuleName { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ExportsFolder { get; set; } + + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string OutputFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeGenerated { get; set; } + + protected override void ProcessRecord() + { + try + { + if (!Directory.Exists(ExportsFolder)) + { + throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist"); + } + + var exportDirectories = Directory.GetDirectories(ExportsFolder); + if (!exportDirectories.Any()) + { + exportDirectories = new[] { ExportsFolder }; + } + /*var loadEnvFile = Path.Combine(OutputFolder, "loadEnv.ps1"); + if (!File.Exists(loadEnvFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@" +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json +}"); + File.WriteAllText(loadEnvFile, sc.ToString()); + }*/ + var utilFile = Path.Combine(OutputFolder, "utils.ps1"); + if (!File.Exists(utilFile)) + { + var sc = new StringBuilder(); + sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) { + if ($allChars) { + return -join ((33..126) | Get-Random -Count $len | % {[char]$_}) + } else { + return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_}) + } +} +function Start-TestSleep { + [CmdletBinding(DefaultParameterSetName = 'SleepBySeconds')] + param( + [parameter(Mandatory = $true, Position = 0, ParameterSetName = 'SleepBySeconds')] + [ValidateRange(0.0, 2147483.0)] + [double] $Seconds, + + [parameter(Mandatory = $true, ParameterSetName = 'SleepByMilliseconds')] + [ValidateRange('NonNegative')] + [Alias('ms')] + [int] $Milliseconds + ) + + if ($TestMode -ne 'playback') { + switch ($PSCmdlet.ParameterSetName) { + 'SleepBySeconds' { + Start-Sleep -Seconds $Seconds + } + 'SleepByMilliseconds' { + Start-Sleep -Milliseconds $Milliseconds + } + } + } +} + +$env = @{} +if ($UsePreviousConfigForRecord) { + $previousEnv = Get-Content (Join-Path $PSScriptRoot 'env.json') | ConvertFrom-Json + $previousEnv.psobject.properties | Foreach-Object { $env[$_.Name] = $_.Value } +} +# Add script method called AddWithCache to $env, when useCache is set true, it will try to get the value from the $env first. +# example: $val = $env.AddWithCache('key', $val, $true) +$env | Add-Member -Type ScriptMethod -Value { param( [string]$key, [object]$val, [bool]$useCache) if ($this.Contains($key) -and $useCache) { return $this[$key] } else { $this[$key] = $val; return $val } } -Name 'AddWithCache' +function setupEnv() { + # Preload subscriptionId and tenant from context, which will be used in test + # as default. You could change them if needed. + $env.SubscriptionId = (Get-AzContext).Subscription.Id + $env.Tenant = (Get-AzContext).Tenant.Id + # For any resources you created for test, you should add it to $env here. + $envFile = 'env.json' + if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' + } + set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env) +} +function cleanupEnv() { + # Clean resources you create for testing +} +"); + File.WriteAllText(utilFile, sc.ToString()); + } + + + + foreach (var exportDirectory in exportDirectories) + { + var outputFolder = OutputFolder; + if (exportDirectory != ExportsFolder) + { + outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory)); + Directory.CreateDirectory(outputFolder); + } + + var variantGroups = GetScriptCmdlets(exportDirectory) + .SelectMany(fi => fi.ToVariants()) + .Where(v => !v.IsDoNotExport) + .GroupBy(v => v.CmdletName) + .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true)) + .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated)); + + foreach (var variantGroup in variantGroups) + { + var sb = new StringBuilder(); + sb.AppendLine($"if(($null -eq $TestName) -or ($TestName -contains '{variantGroup.CmdletName}'))"); + sb.AppendLine(@"{ + $loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1' + if (-Not (Test-Path -Path $loadEnvPath)) { + $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1' + } + . ($loadEnvPath)" + ); + sb.AppendLine($@" $TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'"); + sb.AppendLine(@" $currentPath = $PSScriptRoot + while(-not $mockingPath) { + $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File + $currentPath = Split-Path -Path $currentPath -Parent + } + . ($mockingPath | Select-Object -First 1).FullName +} +"); + + + sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{"); + var variants = variantGroup.Variants + .Where(v => IncludeGenerated || !v.Attributes.OfType().Any()) + .ToList(); + + foreach (var variant in variants) + { + sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{"); + sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw"); + var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine; + sb.AppendLine($"{Indent}}}{variantSeparator}"); + } + sb.AppendLine("}"); + + File.WriteAllText(variantGroup.FilePath, sb.ToString()); + } + } + } + catch (Exception ee) + { + Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}"); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetCommonParameter.cs new file mode 100644 index 00000000000..99599627dfe --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetModuleGuid.cs new file mode 100644 index 00000000000..4bdb99412fc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs new file mode 100644 index 00000000000..a69cfd4f98a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Cmdlets/GetScriptCmdlet.cs @@ -0,0 +1,54 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpers; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + [Cmdlet(VerbsCommon.Get, "ScriptCmdlet")] + [OutputType(typeof(string[]))] + [DoNotExport] + public class GetScriptCmdlet : PSCmdlet + { + [Parameter(Mandatory = true)] + [ValidateNotNullOrEmpty] + public string ScriptFolder { get; set; } + + [Parameter] + public SwitchParameter IncludeDoNotExport { get; set; } + + [Parameter] + public SwitchParameter AsAlias { get; set; } + + [Parameter] + public SwitchParameter AsFunctionInfo { get; set; } + + protected override void ProcessRecord() + { + try + { + var functionInfos = GetScriptCmdlets(this, ScriptFolder) + .Where(fi => IncludeDoNotExport || !fi.ScriptBlock.Attributes.OfType().Any()) + .ToArray(); + if (AsFunctionInfo) + { + WriteObject(functionInfos, true); + return; + } + var aliases = functionInfos.SelectMany(i => i.ScriptBlock.Attributes).ToAliasNames(); + var names = functionInfos.Select(fi => fi.Name).Distinct(); + var output = (AsAlias ? aliases : names).DefaultIfEmpty("''").ToArray(); + WriteObject(output, true); + } + catch (System.Exception ee) + { + System.Console.Error.WriteLine($"{ee.GetType().Name}: {ee.Message}"); + System.Console.Error.WriteLine(ee.StackTrace); + throw ee; + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/CollectionExtensions.cs new file mode 100644 index 00000000000..5937874b624 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs new file mode 100644 index 00000000000..64830c75b15 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/MarkdownRenderer.cs @@ -0,0 +1,122 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal static class MarkdownRenderer + { + public static void WriteMarkdowns(IEnumerable variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder, bool AddComplexInterfaceInfo = true) + { + Directory.CreateDirectory(docsFolder); + var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray(); + + foreach (var markdownInfo in markdownInfos) + { + var sb = new StringBuilder(); + sb.Append(markdownInfo.ToHelpMetadataOutput()); + sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}"); + sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}"); + var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1; + foreach (var syntaxInfo in markdownInfo.SyntaxInfos) + { + sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets)); + } + + sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}"); + foreach (var exampleInfo in markdownInfo.Examples) + { + sb.Append(exampleInfo.ToHelpExampleOutput()); + } + + sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}"); + foreach (var parameter in markdownInfo.Parameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + if (markdownInfo.SupportsShouldProcess) + { + foreach (var parameter in SupportsShouldProcessParameters) + { + sb.Append(parameter.ToHelpParameterOutput()); + } + } + + sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var input in markdownInfo.Inputs) + { + sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}"); + foreach (var output in markdownInfo.Outputs) + { + sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}"); + } + + sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}"); + if (markdownInfo.Aliases.Any()) + { + sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}"); + } + foreach (var alias in markdownInfo.Aliases) + { + sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}"); + } + + if (AddComplexInterfaceInfo) + { + if (markdownInfo.ComplexInterfaceInfos.Any()) + { + sb.Append($"{ComplexParameterHeader}{Environment.NewLine}"); + } + foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos) + { + sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}"); + } + + } + + sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}"); + foreach (var relatedLink in markdownInfo.RelatedLinks) + { + sb.Append($"[{relatedLink}]({relatedLink}){Environment.NewLine}{Environment.NewLine}"); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString()); + } + + WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder); + } + + private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder) + { + var sb = new StringBuilder(); + sb.Append(moduleInfo.ToModulePageMetadataOutput()); + sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}"); + sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}"); + + sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}"); + foreach (var markdownInfo in markdownInfos) + { + sb.Append(markdownInfo.ToModulePageCmdletOutput()); + } + + File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString()); + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsFormatTypes.cs new file mode 100644 index 00000000000..cf3b7477760 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs new file mode 100644 index 00000000000..a635f94a771 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpMarkdownOutputs.cs @@ -0,0 +1,199 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal class HelpMetadataOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public HelpMetadataOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"--- +external help file:{(!String.IsNullOrEmpty(HelpInfo.ExternalHelpFilename) ? $" {HelpInfo.ExternalHelpFilename}" : String.Empty)} +Module Name: {HelpInfo.ModuleName} +online version: {HelpInfo.OnlineVersion} +schema: {HelpInfo.Schema.ToString(3)} +--- + +"; + } + + internal class HelpSyntaxOutput + { + public MarkdownSyntaxHelpInfo SyntaxInfo { get; } + public bool HasMultipleParameterSets { get; } + + public HelpSyntaxOutput(MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) + { + SyntaxInfo = syntaxInfo; + HasMultipleParameterSets = hasMultipleParameterSets; + } + + public override string ToString() + { + var psnText = HasMultipleParameterSets ? $"### {SyntaxInfo.ParameterSetName}{(SyntaxInfo.IsDefault ? " (Default)" : String.Empty)}{Environment.NewLine}" : String.Empty; + return $@"{psnText}``` +{SyntaxInfo.SyntaxText} +``` + +"; + } + } + + internal class HelpExampleOutput + { + private string ExampleTemplate = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + Environment.NewLine; + + private string ExampleTemplateWithOutput = + "{0}{1}" + Environment.NewLine + + "{2}" + Environment.NewLine + "{3}" + Environment.NewLine + "{4}" + Environment.NewLine + Environment.NewLine + + "{5}" + Environment.NewLine + "{6}" + Environment.NewLine + "{7}" + Environment.NewLine + Environment.NewLine + + "{8}" + Environment.NewLine + Environment.NewLine; + + public MarkdownExampleHelpInfo ExampleInfo { get; } + + public HelpExampleOutput(MarkdownExampleHelpInfo exampleInfo) + { + ExampleInfo = exampleInfo; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(ExampleInfo.Output)) + { + return string.Format(ExampleTemplate, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleInfo.Description.ToDescriptionFormat()); + } + else + { + return string.Format(ExampleTemplateWithOutput, + ExampleNameHeader, ExampleInfo.Name, + ExampleCodeHeader, ExampleInfo.Code, ExampleCodeFooter, + ExampleOutputHeader, ExampleInfo.Output, ExampleOutputFooter, + ExampleInfo.Description.ToDescriptionFormat()); ; + } + } + } + + internal class HelpParameterOutput + { + public MarkdownParameterHelpInfo ParameterInfo { get; } + + public HelpParameterOutput(MarkdownParameterHelpInfo parameterInfo) + { + ParameterInfo = parameterInfo; + } + + public override string ToString() + { + var pipelineInputTypes = new[] + { + ParameterInfo.AcceptsPipelineByValue ? "ByValue" : String.Empty, + ParameterInfo.AcceptsPipelineByPropertyName ? "ByPropertyName" : String.Empty + }.JoinIgnoreEmpty(", "); + var pipelineInput = ParameterInfo.AcceptsPipelineByValue || ParameterInfo.AcceptsPipelineByPropertyName + ? $@"{true} ({pipelineInputTypes})" + : false.ToString(); + + return $@"### -{ParameterInfo.Name} +{ParameterInfo.Description.ToDescriptionFormat()} + +```yaml +Type: {ParameterInfo.Type.FullName} +Parameter Sets: {(ParameterInfo.HasAllParameterSets ? "(All)" : ParameterInfo.ParameterSetNames.JoinIgnoreEmpty(", "))} +Aliases:{(ParameterInfo.Aliases.Any() ? $" {ParameterInfo.Aliases.JoinIgnoreEmpty(", ")}" : String.Empty)} + +Required: {ParameterInfo.IsRequired} +Position: {ParameterInfo.Position} +Default value: {ParameterInfo.DefaultValue} +Accept pipeline input: {pipelineInput} +Accept wildcard characters: {ParameterInfo.AcceptsWildcardCharacters} +``` + +"; + } + } + + internal class ModulePageMetadataOutput + { + public PsModuleHelpInfo ModuleInfo { get; } + + private static string HelpLinkPrefix { get; } = @"https://learn.microsoft.com/powershell/module/"; + + public ModulePageMetadataOutput(PsModuleHelpInfo moduleInfo) + { + ModuleInfo = moduleInfo; + } + + public override string ToString() => $@"--- +Module Name: {ModuleInfo.Name} +Module Guid: {ModuleInfo.Guid} +Download Help Link: {HelpLinkPrefix}{ModuleInfo.Name.ToLowerInvariant()} +Help Version: 1.0.0.0 +Locale: en-US +--- + +"; + } + + internal class ModulePageCmdletOutput + { + public MarkdownHelpInfo HelpInfo { get; } + + public ModulePageCmdletOutput(MarkdownHelpInfo helpInfo) + { + HelpInfo = helpInfo; + } + + public override string ToString() => $@"### [{HelpInfo.CmdletName}]({HelpInfo.CmdletName}.md) +{HelpInfo.Synopsis.ToDescriptionFormat()} + +"; + } + + internal static class PsHelpOutputExtensions + { + public static string EscapeAngleBrackets(this string text) => text?.Replace("<", @"\<").Replace(">", @"\>"); + public static string ReplaceSentenceEndWithNewline(this string text) => text?.Replace(". ", $".{Environment.NewLine}").Replace(". ", $".{Environment.NewLine}"); + public static string ReplaceBrWithNewline(this string text) => text?.Replace("
", $"{Environment.NewLine}"); + public static string ToDescriptionFormat(this string text, bool escapeAngleBrackets = true) + { + var description = text?.ReplaceBrWithNewline(); + description = escapeAngleBrackets ? description?.EscapeAngleBrackets() : description; + return description?.ReplaceSentenceEndWithNewline().Trim(); + } + + public const string ExampleNameHeader = "### "; + public const string ExampleCodeHeader = "```powershell"; + public const string ExampleCodeFooter = "```"; + public const string ExampleOutputHeader = "```output"; + public const string ExampleOutputFooter = "```"; + + public static HelpMetadataOutput ToHelpMetadataOutput(this MarkdownHelpInfo helpInfo) => new HelpMetadataOutput(helpInfo); + + public static HelpSyntaxOutput ToHelpSyntaxOutput(this MarkdownSyntaxHelpInfo syntaxInfo, bool hasMultipleParameterSets) => new HelpSyntaxOutput(syntaxInfo, hasMultipleParameterSets); + + public static HelpExampleOutput ToHelpExampleOutput(this MarkdownExampleHelpInfo exampleInfo) => new HelpExampleOutput(exampleInfo); + + public static HelpParameterOutput ToHelpParameterOutput(this MarkdownParameterHelpInfo parameterInfo) => new HelpParameterOutput(parameterInfo); + + public static ModulePageMetadataOutput ToModulePageMetadataOutput(this PsModuleHelpInfo moduleInfo) => new ModulePageMetadataOutput(moduleInfo); + + public static ModulePageCmdletOutput ToModulePageCmdletOutput(this MarkdownHelpInfo helpInfo) => new ModulePageCmdletOutput(helpInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs new file mode 100644 index 00000000000..8092e8a6c9e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsHelpTypes.cs @@ -0,0 +1,202 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal class PsHelpInfo + { + public string CmdletName { get; } + public string ModuleName { get; } + public string Synopsis { get; } + public string Description { get; } + public string AlertText { get; } + public string Category { get; } + public PsHelpLinkInfo OnlineVersion { get; } + public PsHelpLinkInfo[] RelatedLinks { get; } + public bool? HasCommonParameters { get; } + public bool? HasWorkflowCommonParameters { get; } + + public PsHelpTypeInfo[] InputTypes { get; } + public PsHelpTypeInfo[] OutputTypes { get; } + public PsHelpExampleInfo[] Examples { get; set; } + public string[] Aliases { get; } + + public PsParameterHelpInfo[] Parameters { get; } + public PsHelpSyntaxInfo[] Syntax { get; } + + public object Component { get; } + public object Functionality { get; } + public object PsSnapIn { get; } + public object Role { get; } + public string NonTerminatingErrors { get; } + + public PsHelpInfo(PSObject helpObject = null) + { + helpObject = helpObject ?? new PSObject(); + CmdletName = helpObject.GetProperty("Name").NullIfEmpty() ?? helpObject.GetNestedProperty("details", "name"); + ModuleName = helpObject.GetProperty("ModuleName"); + Synopsis = helpObject.GetProperty("Synopsis"); + Description = helpObject.GetProperty("description").EmptyIfNull().ToDescriptionText().NullIfEmpty() ?? + helpObject.GetNestedProperty("details", "description").EmptyIfNull().ToDescriptionText(); + AlertText = helpObject.GetNestedProperty("alertSet", "alert").EmptyIfNull().ToDescriptionText(); + Category = helpObject.GetProperty("Category"); + HasCommonParameters = helpObject.GetProperty("CommonParameters").ToNullableBool(); + HasWorkflowCommonParameters = helpObject.GetProperty("WorkflowCommonParameters").ToNullableBool(); + + var links = helpObject.GetNestedProperty("relatedLinks", "navigationLink").EmptyIfNull().Select(nl => nl.ToLinkInfo()).ToArray(); + OnlineVersion = links.FirstOrDefault(l => l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length == 1); + RelatedLinks = links.Where(l => !l.Text?.ToLowerInvariant().StartsWith("online version:") ?? links.Length != 1).ToArray(); + + InputTypes = helpObject.GetNestedProperty("inputTypes", "inputType").EmptyIfNull().Select(it => it.ToTypeInfo()).ToArray(); + OutputTypes = helpObject.GetNestedProperty("returnValues", "returnValue").EmptyIfNull().Select(rv => rv.ToTypeInfo()).ToArray(); + Examples = helpObject.GetNestedProperty("examples", "example").EmptyIfNull().Select(e => e.ToExampleInfo()).ToArray(); + Aliases = helpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Parameters = helpObject.GetNestedProperty("parameters", "parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + Syntax = helpObject.GetNestedProperty("syntax", "syntaxItem").EmptyIfNull().Select(si => si.ToSyntaxInfo()).ToArray(); + + Component = helpObject.GetProperty("Component"); + Functionality = helpObject.GetProperty("Functionality"); + PsSnapIn = helpObject.GetProperty("PSSnapIn"); + Role = helpObject.GetProperty("Role"); + NonTerminatingErrors = helpObject.GetProperty("nonTerminatingErrors"); + } + } + + internal class PsHelpTypeInfo + { + public string Name { get; } + public string Description { get; } + + public PsHelpTypeInfo(PSObject typeObject) + { + Name = typeObject.GetNestedProperty("type", "name").EmptyIfNull().Trim(); + Description = typeObject.GetProperty("description").EmptyIfNull().ToDescriptionText(); + } + } + + internal class PsHelpLinkInfo + { + public string Uri { get; } + public string Text { get; } + + public PsHelpLinkInfo(PSObject linkObject) + { + Uri = linkObject.GetProperty("uri"); + Text = linkObject.GetProperty("linkText"); + } + } + + internal class PsHelpSyntaxInfo + { + public string CmdletName { get; } + public PsParameterHelpInfo[] Parameters { get; } + + public PsHelpSyntaxInfo(PSObject syntaxObject) + { + CmdletName = syntaxObject.GetProperty("name"); + Parameters = syntaxObject.GetProperty("parameter").EmptyIfNull().Select(p => p.ToPsParameterHelpInfo()).ToArray(); + } + } + + internal class PsHelpExampleInfo + { + public string Title { get; } + public string Code { get; } + public string Output { get; } + public string Remarks { get; } + + public PsHelpExampleInfo(PSObject exampleObject) + { + Title = exampleObject.GetProperty("title"); + Code = exampleObject.GetProperty("code"); + Output = exampleObject.GetProperty("output"); + Remarks = exampleObject.GetProperty("remarks").EmptyIfNull().ToDescriptionText(); + } + public PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) + { + Title = markdownExample.Name; + Code = markdownExample.Code; + Output = markdownExample.Output; + Remarks = markdownExample.Description; + } + + public static implicit operator PsHelpExampleInfo(MarkdownExampleHelpInfo markdownExample) => new PsHelpExampleInfo(markdownExample); + } + + internal class PsParameterHelpInfo + { + public string DefaultValueAsString { get; } + + public string Name { get; } + public string TypeName { get; } + public string Description { get; } + public string SupportsPipelineInput { get; } + public string PositionText { get; } + public string[] ParameterSetNames { get; } + public string[] Aliases { get; } + + public bool? SupportsGlobbing { get; } + public bool? IsRequired { get; } + public bool? IsVariableLength { get; } + public bool? IsDynamic { get; } + + public PsParameterHelpInfo(PSObject parameterHelpObject = null) + { + parameterHelpObject = parameterHelpObject ?? new PSObject(); + DefaultValueAsString = parameterHelpObject.GetProperty("defaultValue"); + Name = parameterHelpObject.GetProperty("name"); + TypeName = parameterHelpObject.GetProperty("parameterValue").NullIfEmpty() ?? parameterHelpObject.GetNestedProperty("type", "name"); + Description = parameterHelpObject.GetProperty("Description").EmptyIfNull().ToDescriptionText(); + SupportsPipelineInput = parameterHelpObject.GetProperty("pipelineInput"); + PositionText = parameterHelpObject.GetProperty("position"); + ParameterSetNames = parameterHelpObject.GetProperty("parameterSetName").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + Aliases = parameterHelpObject.GetProperty("aliases").EmptyIfNull().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries); + + SupportsGlobbing = parameterHelpObject.GetProperty("globbing").ToNullableBool(); + IsRequired = parameterHelpObject.GetProperty("required").ToNullableBool(); + IsVariableLength = parameterHelpObject.GetProperty("variableLength").ToNullableBool(); + IsDynamic = parameterHelpObject.GetProperty("isDynamic").ToNullableBool(); + } + } + + internal class PsModuleHelpInfo + { + public string Name { get; } + public Guid Guid { get; } + public string Description { get; } + + public PsModuleHelpInfo(PSModuleInfo moduleInfo) + : this(moduleInfo?.Name ?? String.Empty, moduleInfo?.Guid ?? Guid.NewGuid(), moduleInfo?.Description ?? String.Empty) + { + } + + public PsModuleHelpInfo(string name, Guid guid, string description) + { + Name = name; + Guid = guid; + Description = description; + } + } + + internal static class HelpTypesExtensions + { + public static PsHelpInfo ToPsHelpInfo(this PSObject helpObject) => new PsHelpInfo(helpObject); + public static PsParameterHelpInfo ToPsParameterHelpInfo(this PSObject parameterHelpObject) => new PsParameterHelpInfo(parameterHelpObject); + + public static string ToDescriptionText(this IEnumerable descriptionObject) => descriptionObject != null + ? String.Join(Environment.NewLine, descriptionObject.Select(dl => dl.GetProperty("Text").EmptyIfNull())).NullIfWhiteSpace() + : null; + public static PsHelpTypeInfo ToTypeInfo(this PSObject typeObject) => new PsHelpTypeInfo(typeObject); + public static PsHelpExampleInfo ToExampleInfo(this PSObject exampleObject) => new PsHelpExampleInfo(exampleObject); + public static PsHelpLinkInfo ToLinkInfo(this PSObject linkObject) => new PsHelpLinkInfo(linkObject); + public static PsHelpSyntaxInfo ToSyntaxInfo(this PSObject syntaxObject) => new PsHelpSyntaxInfo(syntaxObject); + public static PsModuleHelpInfo ToModuleInfo(this PSModuleInfo moduleInfo) => new PsModuleHelpInfo(moduleInfo); + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs new file mode 100644 index 00000000000..e21d8ef3c80 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsMarkdownTypes.cs @@ -0,0 +1,329 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.MarkdownTypesExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsHelpOutputExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal class MarkdownHelpInfo + { + public string ExternalHelpFilename { get; } + public string ModuleName { get; } + public string OnlineVersion { get; } + public Version Schema { get; } + + public string CmdletName { get; } + public string[] Aliases { get; } + public string Synopsis { get; } + public string Description { get; } + + public MarkdownSyntaxHelpInfo[] SyntaxInfos { get; } + public MarkdownExampleHelpInfo[] Examples { get; } + public MarkdownParameterHelpInfo[] Parameters { get; } + + public string[] Inputs { get; } + public string[] Outputs { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + public MarkdownRelatedLinkInfo[] RelatedLinks { get; } + + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public MarkdownHelpInfo(VariantGroup variantGroup, string examplesFolder, string externalHelpFilename = "") + { + ExternalHelpFilename = externalHelpFilename; + ModuleName = variantGroup.RootModuleName != "" ? variantGroup.RootModuleName : variantGroup.ModuleName; + var helpInfo = variantGroup.HelpInfo; + var commentInfo = variantGroup.CommentInfo; + Schema = Version.Parse("2.0.0"); + + CmdletName = variantGroup.CmdletName; + Aliases = (variantGroup.Aliases.NullIfEmpty() ?? helpInfo.Aliases).Where(a => a != "None").ToArray(); + Synopsis = commentInfo.Synopsis; + Description = commentInfo.Description; + + SyntaxInfos = variantGroup.Variants + .Select(v => new MarkdownSyntaxHelpInfo(v, variantGroup.ParameterGroups, v.VariantName == variantGroup.DefaultParameterSetName)) + .OrderByDescending(v => v.IsDefault).ThenBy(v => v.ParameterSetName).ToArray(); + Examples = GetExamplesFromMarkdown(examplesFolder).NullIfEmpty() + ?? helpInfo.Examples.Select(e => e.ToExampleHelpInfo()).ToArray().NullIfEmpty() + ?? DefaultExampleHelpInfos; + + Parameters = variantGroup.ParameterGroups + .Where(pg => !pg.DontShow && !pg.Parameters.All(p => p.IsHidden())) + .Select(pg => new MarkdownParameterHelpInfo( + variantGroup.Variants.SelectMany(v => v.HelpInfo.Parameters).Where(phi => phi.Name == pg.ParameterName).ToArray(), pg)) + .OrderBy(phi => phi.Name).ToArray(); + + Inputs = commentInfo.Inputs; + Outputs = commentInfo.Outputs; + + ComplexInterfaceInfos = variantGroup.ComplexInterfaceInfos; + OnlineVersion = commentInfo.OnlineVersion; + + var relatedLinkLists = new List(); + relatedLinkLists.AddRange(commentInfo.RelatedLinks?.Select(link => new MarkdownRelatedLinkInfo(link))); + relatedLinkLists.AddRange(variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Distinct()?.Select(link => new MarkdownRelatedLinkInfo(link.Url, link.Description))); + RelatedLinks = relatedLinkLists?.ToArray(); + + SupportsShouldProcess = variantGroup.SupportsShouldProcess; + SupportsPaging = variantGroup.SupportsPaging; + } + + private MarkdownExampleHelpInfo[] GetExamplesFromMarkdown(string examplesFolder) + { + var filePath = Path.Combine(examplesFolder, $"{CmdletName}.md"); + if (!Directory.Exists(examplesFolder) || !File.Exists(filePath)) return null; + + var lines = File.ReadAllLines(filePath); + var nameIndices = lines.Select((l, i) => l.StartsWith(ExampleNameHeader) ? i : -1).Where(i => i != -1).ToArray(); + //https://codereview.stackexchange.com/a/187148/68772 + var indexCountGroups = nameIndices.Skip(1).Append(lines.Length).Zip(nameIndices, (next, current) => (NameIndex: current, LineCount: next - current)); + var exampleGroups = indexCountGroups.Select(icg => lines.Skip(icg.NameIndex).Take(icg.LineCount).ToArray()); + return exampleGroups.Select(eg => + { + var name = eg.First().Replace(ExampleNameHeader, String.Empty); + var codeStartIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var codeEndIndex = eg.Select((l, i) => l.StartsWith(ExampleCodeFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i != codeStartIndex); + var code = codeStartIndex.HasValue && codeEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(codeStartIndex.Value + 1).Take(codeEndIndex.Value - (codeStartIndex.Value + 1))) + : String.Empty; + var outputStartIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputHeader) ? (int?)i : null).FirstOrDefault(i => i.HasValue); + var outputEndIndex = eg.Select((l, i) => l.StartsWith(ExampleOutputFooter) ? (int?)i : null).FirstOrDefault(i => i.HasValue && i > outputStartIndex); + var output = outputStartIndex.HasValue && outputEndIndex.HasValue + ? String.Join(Environment.NewLine, eg.Skip(outputStartIndex.Value + 1).Take(outputEndIndex.Value - (outputStartIndex.Value + 1))) + : String.Empty; + var descriptionStartIndex = (outputEndIndex ?? (codeEndIndex ?? 0)) + 1; + descriptionStartIndex = String.IsNullOrWhiteSpace(eg[descriptionStartIndex]) ? descriptionStartIndex + 1 : descriptionStartIndex; + var descriptionEndIndex = eg.Length - 1; + descriptionEndIndex = String.IsNullOrWhiteSpace(eg[descriptionEndIndex]) ? descriptionEndIndex - 1 : descriptionEndIndex; + var description = String.Join(Environment.NewLine, eg.Skip(descriptionStartIndex).Take((descriptionEndIndex + 1) - descriptionStartIndex)); + return new MarkdownExampleHelpInfo(name, code, output, description); + }).ToArray(); + } + } + + internal class MarkdownSyntaxHelpInfo + { + public Variant Variant { get; } + public bool IsDefault { get; } + public string ParameterSetName { get; } + public Parameter[] Parameters { get; } + public string SyntaxText { get; } + + public MarkdownSyntaxHelpInfo(Variant variant, ParameterGroup[] parameterGroups, bool isDefault) + { + Variant = variant; + IsDefault = isDefault; + ParameterSetName = Variant.VariantName; + Parameters = Variant.Parameters + .Where(p => !p.DontShow && !p.IsHidden()).OrderByDescending(p => p.IsMandatory) + //https://stackoverflow.com/a/6461526/294804 + .ThenByDescending(p => p.Position.HasValue).ThenBy(p => p.Position) + // Use the OrderCategory of the parameter group because the final order category is the highest of the group, and not the order category of the individual parameters from the variants. + .ThenBy(p => parameterGroups.First(pg => pg.ParameterName == p.ParameterName).OrderCategory).ThenBy(p => p.ParameterName).ToArray(); + SyntaxText = CreateSyntaxFormat(); + } + + //https://github.com/PowerShell/platyPS/blob/a607a926bfffe1e1a1e53c19e0057eddd0c07611/src/Markdown.MAML/Renderer/Markdownv2Renderer.cs#L29-L32 + private const int SyntaxLineWidth = 110; + private string CreateSyntaxFormat() + { + var parameterStrings = Parameters.Select(p => p.ToPropertySyntaxOutput().ToString()); + if (Variant.SupportsShouldProcess) + { + parameterStrings = parameterStrings.Append(" [-Confirm]").Append(" [-WhatIf]"); + } + parameterStrings = parameterStrings.Append(" []"); + + var lines = new List(20); + return parameterStrings.Aggregate(Variant.CmdletName, (current, ps) => + { + var combined = current + ps; + if (combined.Length <= SyntaxLineWidth) return combined; + + lines.Add(current); + return ps; + }, last => + { + lines.Add(last); + return String.Join(Environment.NewLine, lines); + }); + } + } + + internal class MarkdownExampleHelpInfo + { + public string Name { get; } + public string Code { get; } + public string Output { get; } + public string Description { get; } + + public MarkdownExampleHelpInfo(string name, string code, string output, string description) + { + Name = name; + Code = code; + Output = output; + Description = description; + } + } + + internal class MarkdownParameterHelpInfo + { + public string Name { get; set; } + public string Description { get; set; } + public Type Type { get; set; } + public string Position { get; set; } + public string DefaultValue { get; set; } + + public bool HasAllParameterSets { get; set; } + public string[] ParameterSetNames { get; set; } + public string[] Aliases { get; set; } + + public bool IsRequired { get; set; } + public bool IsDynamic { get; set; } + public bool AcceptsPipelineByValue { get; set; } + public bool AcceptsPipelineByPropertyName { get; set; } + public bool AcceptsWildcardCharacters { get; set; } + + // For use by common parameters that have no backing data in the objects themselves. + public MarkdownParameterHelpInfo() { } + + public MarkdownParameterHelpInfo(PsParameterHelpInfo[] parameterHelpInfos, ParameterGroup parameterGroup) + { + Name = parameterGroup.ParameterName; + Description = parameterGroup.Description.NullIfEmpty() + ?? parameterHelpInfos.Select(phi => phi.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + Type = parameterGroup.ParameterType; + Position = parameterGroup.FirstPosition?.ToString() + ?? parameterHelpInfos.Select(phi => phi.PositionText).FirstOrDefault(d => !String.IsNullOrEmpty(d)).ToUpperFirstCharacter().NullIfEmpty() + ?? "Named"; + // This no longer uses firstHelpInfo.DefaultValueAsString since it seems to be broken. For example, it has a value of 0 for Int32, but no default value was declared. + DefaultValue = parameterGroup.DefaultInfo?.Script ?? "None"; + + HasAllParameterSets = parameterGroup.HasAllVariants; + ParameterSetNames = (parameterGroup.Parameters.Select(p => p.VariantName).ToArray().NullIfEmpty() + ?? parameterHelpInfos.SelectMany(phi => phi.ParameterSetNames).Distinct()) + .OrderBy(psn => psn).ToArray(); + Aliases = parameterGroup.Aliases.NullIfEmpty() ?? parameterHelpInfos.SelectMany(phi => phi.Aliases).ToArray(); + + IsRequired = parameterHelpInfos.Select(phi => phi.IsRequired).FirstOrDefault(r => r == true) ?? parameterGroup.Parameters.Any(p => p.IsMandatory); + IsDynamic = parameterHelpInfos.Select(phi => phi.IsDynamic).FirstOrDefault(d => d == true) ?? false; + AcceptsPipelineByValue = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByValue")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipeline; + AcceptsPipelineByPropertyName = parameterHelpInfos.Select(phi => phi.SupportsPipelineInput?.Contains("ByPropertyName")).FirstOrDefault(bv => bv == true) ?? parameterGroup.ValueFromPipelineByPropertyName; + AcceptsWildcardCharacters = parameterGroup.SupportsWildcards; + } + } + + internal class MarkdownRelatedLinkInfo + { + public string Url { get; } + public string Description { get; } + + public MarkdownRelatedLinkInfo(string url) + { + Url = url; + } + + public MarkdownRelatedLinkInfo(string url, string description) + { + Url = url; + Description = description; + } + + public override string ToString() + { + if (string.IsNullOrEmpty(Description)) + { + return Url; + } + else + { + return $@"[{Description}]({Url})"; + + } + + } + } + + internal static class MarkdownTypesExtensions + { + public static MarkdownExampleHelpInfo ToExampleHelpInfo(this PsHelpExampleInfo exampleInfo) => new MarkdownExampleHelpInfo(exampleInfo.Title, exampleInfo.Code, exampleInfo.Output, exampleInfo.Remarks); + + public static MarkdownExampleHelpInfo[] DefaultExampleHelpInfos = + { + new MarkdownExampleHelpInfo("Example 1: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + new MarkdownExampleHelpInfo("Example 2: {{ Add title here }}", $@"{{{{ Add code here }}}}", $@"{{{{ Add output here (remove the output block if the example doesn't have an output) }}}}", @"{{ Add description here }}"), + }; + + public static MarkdownParameterHelpInfo[] SupportsShouldProcessParameters = + { + new MarkdownParameterHelpInfo + { + Name = "Confirm", + Description ="Prompts you for confirmation before running the cmdlet.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "cf" } + }, + new MarkdownParameterHelpInfo + { + Name = "WhatIf", + Description ="Shows what would happen if the cmdlet runs. The cmdlet is not run.", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new [] { "wi" } + } + }; + + public static MarkdownParameterHelpInfo[] SupportsPagingParameters = + { + new MarkdownParameterHelpInfo + { + Name = "First", + Description ="Gets only the first 'n' objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "IncludeTotalCount", + Description ="Reports the number of objects in the data set (an integer) followed by the objects. If the cmdlet cannot determine the total count, it returns \"Unknown total count\".", + Type = typeof(SwitchParameter), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + }, + new MarkdownParameterHelpInfo + { + Name = "Skip", + Description ="Ignores the first 'n' objects and then gets the remaining objects.", + Type = typeof(ulong), + Position = "Named", + DefaultValue = "None", + HasAllParameterSets = true, + ParameterSetNames = new [] { "(All)" }, + Aliases = new string[0] + } + }; + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs new file mode 100644 index 00000000000..b6cc7b29cee --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyOutputs.cs @@ -0,0 +1,662 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Text; +using System.Text.RegularExpressions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal class OutputTypeOutput + { + public PSTypeName[] OutputTypes { get; } + + public OutputTypeOutput(IEnumerable outputTypes) + { + OutputTypes = outputTypes.ToArray(); + } + + public override string ToString() => OutputTypes != null && OutputTypes.Any() ? $"[OutputType({OutputTypes.Select(ot => $"[{ot}]").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class CmdletBindingOutput + { + public VariantGroup VariantGroup { get; } + + public CmdletBindingOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + + public override string ToString() + { + var dpsText = VariantGroup.DefaultParameterSetName.IsValidDefaultParameterSetName() ? $"DefaultParameterSetName='{VariantGroup.DefaultParameterSetName}'" : String.Empty; + var sspText = VariantGroup.SupportsShouldProcess ? $"SupportsShouldProcess{ItemSeparator}ConfirmImpact='Medium'" : String.Empty; + var pbText = $"PositionalBinding={false.ToPsBool()}"; + var propertyText = new[] { dpsText, pbText, sspText }.JoinIgnoreEmpty(ItemSeparator); + return $"[CmdletBinding({propertyText})]{Environment.NewLine}"; + } + } + + internal class ParameterOutput + { + public Parameter Parameter { get; } + public bool HasMultipleVariantsInVariantGroup { get; } + public bool HasAllVariantsInParameterGroup { get; } + + public ParameterOutput(Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) + { + Parameter = parameter; + HasMultipleVariantsInVariantGroup = hasMultipleVariantsInVariantGroup; + HasAllVariantsInParameterGroup = hasAllVariantsInParameterGroup; + } + + public override string ToString() + { + var psnText = HasMultipleVariantsInVariantGroup && !HasAllVariantsInParameterGroup ? $"ParameterSetName='{Parameter.VariantName}'" : String.Empty; + var positionText = Parameter.Position != null ? $"Position={Parameter.Position}" : String.Empty; + var mandatoryText = Parameter.IsMandatory ? "Mandatory" : String.Empty; + var dontShowText = Parameter.DontShow ? "DontShow" : String.Empty; + var vfpText = Parameter.ValueFromPipeline ? "ValueFromPipeline" : String.Empty; + var vfpbpnText = Parameter.ValueFromPipelineByPropertyName ? "ValueFromPipelineByPropertyName" : String.Empty; + var propertyText = new[] { psnText, positionText, mandatoryText, dontShowText, vfpText, vfpbpnText }.JoinIgnoreEmpty(ItemSeparator); + return $"{Indent}[Parameter({propertyText})]{Environment.NewLine}"; + } + } + + internal class AliasOutput + { + public string[] Aliases { get; } + public bool IncludeIndent { get; } + + public AliasOutput(string[] aliases, bool includeIndent = false) + { + Aliases = aliases; + IncludeIndent = includeIndent; + } + + public override string ToString() => Aliases?.Any() ?? false ? $"{(IncludeIndent ? Indent : String.Empty)}[Alias({Aliases.Select(an => $"'{an}'").JoinIgnoreEmpty(ItemSeparator)})]{Environment.NewLine}" : String.Empty; + } + + internal class ValidateNotNullOutput + { + public bool HasValidateNotNull { get; } + + public ValidateNotNullOutput(bool hasValidateNotNull) + { + HasValidateNotNull = hasValidateNotNull; + } + + public override string ToString() => HasValidateNotNull ? $"{Indent}[ValidateNotNull()]{Environment.NewLine}" : String.Empty; + } + + internal class AllowEmptyArrayOutput + { + public bool HasAllowEmptyArray { get; } + + public AllowEmptyArrayOutput(bool hasAllowEmptyArray) + { + HasAllowEmptyArray = hasAllowEmptyArray; + } + + public override string ToString() => HasAllowEmptyArray ? $"{Indent}[AllowEmptyCollection()]{Environment.NewLine}" : String.Empty; + } + internal class ArgumentCompleterOutput + { + public CompleterInfo CompleterInfo { get; } + + public ArgumentCompleterOutput(CompleterInfo completerInfo) + { + CompleterInfo = completerInfo; + } + + public override string ToString() => CompleterInfo != null + ? $"{Indent}[ArgumentCompleter({(CompleterInfo.IsTypeCompleter ? $"[{CompleterInfo.Type.Unwrap().ToPsType()}]" : $"{{{CompleterInfo.Script.ToPsSingleLine("; ")}}}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class PSArgumentCompleterOutput : ArgumentCompleterOutput + { + public PSArgumentCompleterInfo PSArgumentCompleterInfo { get; } + + public PSArgumentCompleterOutput(PSArgumentCompleterInfo completerInfo) : base(completerInfo) + { + PSArgumentCompleterInfo = completerInfo; + } + + + public override string ToString() => PSArgumentCompleterInfo != null + ? $"{Indent}[{typeof(PSArgumentCompleterAttribute)}({(PSArgumentCompleterInfo.IsTypeCompleter ? $"[{PSArgumentCompleterInfo.Type.Unwrap().ToPsType()}]" : $"{PSArgumentCompleterInfo.ResourceTypes?.Select(r => $"\"{r}\"")?.JoinIgnoreEmpty(", ")}")})]{Environment.NewLine}" + : String.Empty; + } + + internal class DefaultInfoOutput + { + public bool HasDefaultInfo { get; } + public DefaultInfo DefaultInfo { get; } + + public DefaultInfoOutput(ParameterGroup parameterGroup) + { + HasDefaultInfo = parameterGroup.HasDefaultInfo; + DefaultInfo = parameterGroup.DefaultInfo; + } + + public override string ToString() + { + var nameText = !String.IsNullOrEmpty(DefaultInfo?.Name) ? $"Name='{DefaultInfo?.Name}'" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(DefaultInfo?.Description) ? $"Description='{DefaultInfo?.Description.ToPsStringLiteral()}'" : String.Empty; + var scriptText = !String.IsNullOrEmpty(DefaultInfo?.Script) ? $"Script='{DefaultInfo?.Script.ToPsSingleLine("; ")}'" : String.Empty; + var propertyText = new[] { nameText, descriptionText, scriptText }.JoinIgnoreEmpty(ItemSeparator); + return HasDefaultInfo ? $"{Indent}[{typeof(DefaultInfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class ParameterTypeOutput + { + public Type ParameterType { get; } + + public ParameterTypeOutput(Type parameterType) + { + ParameterType = parameterType; + } + + public override string ToString() => $"{Indent}[{ParameterType.ToPsType()}]{Environment.NewLine}"; + } + + internal class ParameterNameOutput + { + public string ParameterName { get; } + public bool IsLast { get; } + + public ParameterNameOutput(string parameterName, bool isLast) + { + ParameterName = parameterName; + IsLast = isLast; + } + + public override string ToString() => $"{Indent}${{{ParameterName}}}{(IsLast ? String.Empty : $",{Environment.NewLine}")}{Environment.NewLine}"; + } + + internal class BaseOutput + { + public VariantGroup VariantGroup { get; } + + protected static readonly bool IsAzure = Convert.ToBoolean(@"true"); + + public BaseOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + } + public string ClearTelemetryContext() + { + return (!VariantGroup.IsInternal && IsAzure) ? $@"{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext()" : ""; + } + } + + internal class BeginOutput : BaseOutput + { + public BeginOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + public string GetProcessCustomAttributesAtRuntime() + { + return VariantGroup.IsInternal ? "" : IsAzure ? $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet] +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}if ($null -ne $MyInvocation.MyCommand -and [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets -notcontains $MyInvocation.MyCommand.Name -and [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.MessageAttributeHelper]::ContainsPreviewAttribute($cmdInfo, $MyInvocation)){{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PromptedPreviewMessageCmdlets.Enqueue($MyInvocation.MyCommand.Name) +{Indent}{Indent}}}" : $@"{Indent}{Indent}$cmdInfo = Get-Command -Name $mapping[$parameterSet]{Environment.NewLine}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.MessageAttributeHelper]::ProcessCustomAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.MessageAttributeHelper]::ProcessPreviewMessageAttributesAtRuntime($cmdInfo, $MyInvocation, $parameterSet, $PSCmdlet)"; + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}if ($null -eq [Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion) {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet]::PowerShellVersion = $PSVersionTable.PSVersion.ToString() +{Indent}{Indent}}} +{Indent}{Indent}$preTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId =(New-Guid).ToString() +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.module]::Instance.Telemetry.Invoke('Create', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}$internalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}{Indent}if ($internalCalledCmdlets -eq '') {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} else {{ +{Indent}{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets += ',' + $MyInvocation.MyCommand.Name +{Indent}{Indent}{Indent}}} +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = 'internal' +{Indent}{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"begin {{ +{Indent}try {{ +{Indent}{Indent}$outBuffer = $null +{Indent}{Indent}if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ +{Indent}{Indent}{Indent}$PSBoundParameters['OutBuffer'] = 1 +{Indent}{Indent}}} +{Indent}{Indent}$parameterSet = $PSCmdlet.ParameterSetName +{GetTelemetry()} +{GetParameterSetToCmdletMapping()}{GetDefaultValuesStatements()} +{GetProcessCustomAttributesAtRuntime()} +{Indent}{Indent}$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand(($mapping[$parameterSet]), [System.Management.Automation.CommandTypes]::Cmdlet) +{Indent}{Indent}$scriptCmd = {{& $wrappedCmd @PSBoundParameters}} +{Indent}{Indent}$steppablePipeline = $scriptCmd.GetSteppablePipeline($MyInvocation.CommandOrigin) +{Indent}{Indent}$steppablePipeline.Begin($PSCmdlet) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} + +"; + + private string GetParameterSetToCmdletMapping() + { + var sb = new StringBuilder(); + sb.AppendLine($"{Indent}{Indent}$mapping = @{{"); + foreach (var variant in VariantGroup.Variants) + { + sb.AppendLine($@"{Indent}{Indent}{Indent}{variant.VariantName} = '{variant.PrivateModuleName}\{variant.PrivateCmdletName}';"); + } + sb.Append($"{Indent}{Indent}}}"); + return sb.ToString(); + } + + private string GetDefaultValuesStatements() + { + var defaultInfos = VariantGroup.ParameterGroups.Where(pg => pg.HasDefaultInfo).Select(pg => pg.DefaultInfo).ToArray(); + var sb = new StringBuilder(); + + foreach (var defaultInfo in defaultInfos) + { + var variantListString = defaultInfo.ParameterGroup.VariantNames.ToPsList(); + var parameterName = defaultInfo.ParameterGroup.ParameterName; + sb.AppendLine(); + var setCondition = " "; + if (!String.IsNullOrEmpty(defaultInfo.SetCondition)) + { + setCondition = $" -and {defaultInfo.SetCondition}"; + } + //Yabo: this is bad to hard code the subscription id, but autorest load input README.md reversely (entry readme -> required readme), there are no other way to + //override default value set in required readme + if ("SubscriptionId".Equals(parameterName)) + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$testPlayback = $false"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['HttpPipelinePrepend'] | Foreach-Object {{ if ($_) {{ $testPlayback = $testPlayback -or ('Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PipelineMock' -eq $_.Target.GetType().FullName -and 'Playback' -eq $_.Target.Mode) }} }}"); + sb.AppendLine($"{Indent}{Indent}{Indent}if ($testPlayback) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = . (Join-Path $PSScriptRoot '..' 'utils' 'Get-SubscriptionIdTestSafe.ps1')"); + sb.AppendLine($"{Indent}{Indent}{Indent}}} else {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.AppendLine($"{Indent}{Indent}{Indent}}}"); + sb.Append($"{Indent}{Indent}}}"); + } + else + { + sb.AppendLine($"{Indent}{Indent}if (({variantListString}) -contains $parameterSet -and -not $PSBoundParameters.ContainsKey('{parameterName}'){setCondition}) {{"); + sb.AppendLine($"{Indent}{Indent}{Indent}$PSBoundParameters['{parameterName}'] = {defaultInfo.Script}"); + sb.Append($"{Indent}{Indent}}}"); + } + + } + return sb.ToString(); + } + + } + + internal class ProcessOutput : BaseOutput + { + public ProcessOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetFinally() + { + if (IsAzure && !VariantGroup.IsInternal) + { + return $@" +{Indent}finally {{ +{Indent}{Indent}$backupTelemetryId = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId +{Indent}{Indent}$backupInternalCalledCmdlets = [Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}}} +"; + } + return ""; + } + public override string ToString() => $@"process {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.Process($_) +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +{GetFinally()} +}} +"; + } + + internal class EndOutput : BaseOutput + { + public EndOutput(VariantGroup variantGroup) : base(variantGroup) + { + } + + private string GetTelemetry() + { + if (!VariantGroup.IsInternal && IsAzure) + { + return $@" +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $backupTelemetryId +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::InternalCalledCmdlets = $backupInternalCalledCmdlets +{Indent}{Indent}if ($preTelemetryId -eq '') {{ +{Indent}{Indent}{Indent}[Microsoft.Azure.PowerShell.Cmdlets.Qumulo.module]::Instance.Telemetry.Invoke('Send', $MyInvocation, $parameterSet, $PSCmdlet) +{Indent}{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::ClearTelemetryContext() +{Indent}{Indent}}} +{Indent}{Indent}[Microsoft.WindowsAzure.Commands.Common.MetricHelper]::TelemetryId = $preTelemetryId +"; + } + return ""; + } + public override string ToString() => $@"end {{ +{Indent}try {{ +{Indent}{Indent}$steppablePipeline.End() +{GetTelemetry()} +{Indent}}} catch {{ +{ClearTelemetryContext()} +{Indent}{Indent}throw +{Indent}}} +}} +"; + } + + internal class HelpCommentOutput + { + public VariantGroup VariantGroup { get; } + public CommentInfo CommentInfo { get; } + + public HelpCommentOutput(VariantGroup variantGroup) + { + VariantGroup = variantGroup; + CommentInfo = variantGroup.CommentInfo; + } + + public override string ToString() + { + var inputs = String.Join(Environment.NewLine, CommentInfo.Inputs.Select(i => $".Inputs{Environment.NewLine}{i}")); + var inputsText = !String.IsNullOrEmpty(inputs) ? $"{Environment.NewLine}{inputs}" : String.Empty; + var outputs = String.Join(Environment.NewLine, CommentInfo.Outputs.Select(o => $".Outputs{Environment.NewLine}{o}")); + var outputsText = !String.IsNullOrEmpty(outputs) ? $"{Environment.NewLine}{outputs}" : String.Empty; + var notes = String.Join($"{Environment.NewLine}{Environment.NewLine}", VariantGroup.ComplexInterfaceInfos.Select(cii => cii.ToNoteOutput())); + var notesText = !String.IsNullOrEmpty(notes) ? $"{Environment.NewLine}.Notes{Environment.NewLine}{ComplexParameterHeader}{notes}" : String.Empty; + var relatedLinks = String.Join(Environment.NewLine, CommentInfo.RelatedLinks.Select(l => $".Link{Environment.NewLine}{l}")); + var relatedLinksText = !String.IsNullOrEmpty(relatedLinks) ? $"{Environment.NewLine}{relatedLinks}" : String.Empty; + var externalUrls = String.Join(Environment.NewLine, CommentInfo.ExternalUrls.Select(l => $".Link{Environment.NewLine}{l}")); + var externalUrlsText = !String.IsNullOrEmpty(externalUrls) ? $"{Environment.NewLine}{externalUrls}" : String.Empty; + var examples = ""; + foreach (var example in VariantGroup.HelpInfo.Examples) + { + examples = examples + ".Example" + "\r\n" + example.Code + "\r\n"; + } + return $@"<# +.Synopsis +{CommentInfo.Synopsis.ToDescriptionFormat(false)} +.Description +{CommentInfo.Description.ToDescriptionFormat(false)} +{examples}{inputsText}{outputsText}{notesText} +.Link +{CommentInfo.OnlineVersion}{relatedLinksText}{externalUrlsText} +#> +"; + } + } + + internal class ParameterDescriptionOutput + { + public string Description { get; } + + public ParameterDescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) + ? Description.ToDescriptionFormat(false).NormalizeNewLines() + .Split(new[] { Environment.NewLine }, StringSplitOptions.None) + .Aggregate(String.Empty, (c, n) => c + $"{Indent}# {n}{Environment.NewLine}") + : String.Empty; + } + + internal class ProfileOutput + { + public string ProfileName { get; } + + public ProfileOutput(string profileName) + { + ProfileName = profileName; + } + + public override string ToString() => ProfileName != NoProfiles ? $"[{typeof(ProfileAttribute).ToPsAttributeType()}('{ProfileName}')]{Environment.NewLine}" : String.Empty; + } + + internal class DescriptionOutput + { + public string Description { get; } + + public DescriptionOutput(string description) + { + Description = description; + } + + public override string ToString() => !String.IsNullOrEmpty(Description) ? $"[{typeof(DescriptionAttribute).ToPsAttributeType()}('{Description.ToPsStringLiteral()}')]{Environment.NewLine}" : String.Empty; + } + + internal class ParameterCategoryOutput + { + public ParameterCategory Category { get; } + + public ParameterCategoryOutput(ParameterCategory category) + { + Category = category; + } + + public override string ToString() => $"{Indent}[{typeof(CategoryAttribute).ToPsAttributeType()}('{Category}')]{Environment.NewLine}"; + } + + internal class InfoOutput + { + public InfoAttribute Info { get; } + public Type ParameterType { get; } + + public InfoOutput(InfoAttribute info, Type parameterType) + { + Info = info; + ParameterType = parameterType; + } + + public override string ToString() + { + // Rendering of InfoAttribute members that are not used currently + /*var serializedNameText = Info.SerializedName != null ? $"SerializedName='{Info.SerializedName}'" : String.Empty; + var readOnlyText = Info.ReadOnly ? "ReadOnly" : String.Empty; + var descriptionText = !String.IsNullOrEmpty(Info.Description) ? $"Description='{Info.Description.ToPsStringLiteral()}'" : String.Empty;*/ + + var requiredText = Info.Required ? "Required" : String.Empty; + var unwrappedType = ParameterType.Unwrap(); + var hasValidPossibleTypes = Info.PossibleTypes.Any(pt => pt != unwrappedType); + var possibleTypesText = hasValidPossibleTypes + ? $"PossibleTypes=({Info.PossibleTypes.Select(pt => $"[{pt.ToPsType()}]").JoinIgnoreEmpty(ItemSeparator)})" + : String.Empty; + var propertyText = new[] { /*serializedNameText, */requiredText,/* readOnlyText,*/ possibleTypesText/*, descriptionText*/ }.JoinIgnoreEmpty(ItemSeparator); + return hasValidPossibleTypes ? $"{Indent}[{typeof(InfoAttribute).ToPsAttributeType()}({propertyText})]{Environment.NewLine}" : String.Empty; + } + } + + internal class PropertySyntaxOutput + { + public string ParameterName { get; } + public Type ParameterType { get; } + public bool IsMandatory { get; } + public int? Position { get; } + + public bool IncludeSpace { get; } + public bool IncludeDash { get; } + + public PropertySyntaxOutput(Parameter parameter) + { + ParameterName = parameter.ParameterName; + ParameterType = parameter.ParameterType; + IsMandatory = parameter.IsMandatory; + Position = parameter.Position; + IncludeSpace = true; + IncludeDash = true; + } + + public PropertySyntaxOutput(ComplexInterfaceInfo complexInterfaceInfo) + { + ParameterName = complexInterfaceInfo.Name; + ParameterType = complexInterfaceInfo.Type; + IsMandatory = complexInterfaceInfo.Required; + Position = null; + IncludeSpace = false; + IncludeDash = false; + } + + public override string ToString() + { + var leftOptional = !IsMandatory ? "[" : String.Empty; + var leftPositional = Position != null ? "[" : String.Empty; + var rightPositional = Position != null ? "]" : String.Empty; + var type = ParameterType != typeof(SwitchParameter) ? $" <{ParameterType.ToSyntaxTypeName()}>" : String.Empty; + var rightOptional = !IsMandatory ? "]" : String.Empty; + var space = IncludeSpace ? " " : String.Empty; + var dash = IncludeDash ? "-" : String.Empty; + return $"{space}{leftOptional}{leftPositional}{dash}{ParameterName}{rightPositional}{type}{rightOptional}"; + } + } + + internal static class PsProxyOutputExtensions + { + public const string NoParameters = "__NoParameters"; + + public const string AllParameterSets = "__AllParameterSets"; + + public const string HalfIndent = " "; + + public const string Indent = HalfIndent + HalfIndent; + + public const string ItemSeparator = ", "; + + public static readonly string ComplexParameterHeader = $"COMPLEX PARAMETER PROPERTIES{Environment.NewLine}{Environment.NewLine}To create the parameters described below, construct a hash table containing the appropriate properties. For information on hash tables, run Get-Help about_Hash_Tables.{Environment.NewLine}{Environment.NewLine}"; + + public static string ToPsBool(this bool value) => $"${value.ToString().ToLowerInvariant()}"; + + public static string ToPsType(this Type type) + { + var regex = new Regex(@"^(.*)`{1}\d+(.*)$"); + var typeText = type.ToString(); + var match = regex.Match(typeText); + return match.Success ? $"{match.Groups[1]}{match.Groups[2]}" : typeText; + } + + public static string ToPsAttributeType(this Type type) => type.ToPsType().RemoveEnd("Attribute"); + + // https://stackoverflow.com/a/5284606/294804 + private static string RemoveEnd(this string text, string suffix) => text.EndsWith(suffix) ? text.Substring(0, text.Length - suffix.Length) : text; + + public static string ToPsSingleLine(this string value, string replacer = " ") => value.ReplaceNewLines(replacer, new[] { "
", "\r\n", "\n" }); + + public static string ToPsStringLiteral(this string value) => value?.Replace("'", "''").Replace("‘", "''").Replace("’", "''").ToPsSingleLine().Trim() ?? String.Empty; + + public static string JoinIgnoreEmpty(this IEnumerable values, string separator) => String.Join(separator, values?.Where(v => !String.IsNullOrEmpty(v))); + + // https://stackoverflow.com/a/41961738/294804 + public static string ToSyntaxTypeName(this Type type) + { + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + return $"{type.GetGenericArguments().First().ToSyntaxTypeName()}?"; + } + + if (type.IsGenericType) + { + var genericTypes = String.Join(ItemSeparator, type.GetGenericArguments().Select(ToSyntaxTypeName)); + return $"{type.Name.Split('`').First()}<{genericTypes}>"; + } + + return type.Name; + } + + public static OutputTypeOutput ToOutputTypeOutput(this IEnumerable outputTypes) => new OutputTypeOutput(outputTypes); + + public static CmdletBindingOutput ToCmdletBindingOutput(this VariantGroup variantGroup) => new CmdletBindingOutput(variantGroup); + + public static ParameterOutput ToParameterOutput(this Parameter parameter, bool hasMultipleVariantsInVariantGroup, bool hasAllVariantsInParameterGroup) => new ParameterOutput(parameter, hasMultipleVariantsInVariantGroup, hasAllVariantsInParameterGroup); + + public static AliasOutput ToAliasOutput(this string[] aliases, bool includeIndent = false) => new AliasOutput(aliases, includeIndent); + + public static ValidateNotNullOutput ToValidateNotNullOutput(this bool hasValidateNotNull) => new ValidateNotNullOutput(hasValidateNotNull); + + public static AllowEmptyArrayOutput ToAllowEmptyArray(this bool hasAllowEmptyArray) => new AllowEmptyArrayOutput(hasAllowEmptyArray); + + public static ArgumentCompleterOutput ToArgumentCompleterOutput(this CompleterInfo completerInfo) => (completerInfo is PSArgumentCompleterInfo psArgumentCompleterInfo) ? psArgumentCompleterInfo.ToArgumentCompleterOutput() : new ArgumentCompleterOutput(completerInfo); + + public static PSArgumentCompleterOutput ToArgumentCompleterOutput(this PSArgumentCompleterInfo completerInfo) => new PSArgumentCompleterOutput(completerInfo); + + public static DefaultInfoOutput ToDefaultInfoOutput(this ParameterGroup parameterGroup) => new DefaultInfoOutput(parameterGroup); + + public static ParameterTypeOutput ToParameterTypeOutput(this Type parameterType) => new ParameterTypeOutput(parameterType); + + public static ParameterNameOutput ToParameterNameOutput(this string parameterName, bool isLast) => new ParameterNameOutput(parameterName, isLast); + + public static BeginOutput ToBeginOutput(this VariantGroup variantGroup) => new BeginOutput(variantGroup); + + public static ProcessOutput ToProcessOutput(this VariantGroup variantGroup) => new ProcessOutput(variantGroup); + + public static EndOutput ToEndOutput(this VariantGroup variantGroup) => new EndOutput(variantGroup); + + public static HelpCommentOutput ToHelpCommentOutput(this VariantGroup variantGroup) => new HelpCommentOutput(variantGroup); + + public static ParameterDescriptionOutput ToParameterDescriptionOutput(this string description) => new ParameterDescriptionOutput(description); + + public static ProfileOutput ToProfileOutput(this string profileName) => new ProfileOutput(profileName); + + public static DescriptionOutput ToDescriptionOutput(this string description) => new DescriptionOutput(description); + + public static ParameterCategoryOutput ToParameterCategoryOutput(this ParameterCategory category) => new ParameterCategoryOutput(category); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this Parameter parameter) => new PropertySyntaxOutput(parameter); + + public static PropertySyntaxOutput ToPropertySyntaxOutput(this ComplexInterfaceInfo complexInterfaceInfo) => new PropertySyntaxOutput(complexInterfaceInfo); + + public static InfoOutput ToInfoOutput(this InfoAttribute info, Type parameterType) => new InfoOutput(info, parameterType); + + public static string ToNoteOutput(this ComplexInterfaceInfo complexInterfaceInfo, string currentIndent = "", bool includeDashes = false, bool includeBackticks = false, bool isFirst = true) + { + string RenderProperty(ComplexInterfaceInfo info, string indent, bool dash, bool backtick) => + $"{indent}{(dash ? "- " : String.Empty)}{(backtick ? "`" : String.Empty)}{info.ToPropertySyntaxOutput()}{(backtick ? "`" : String.Empty)}: {info.Description}"; + + var nested = complexInterfaceInfo.NestedInfos.Select(ni => + { + var nestedIndent = $"{currentIndent}{HalfIndent}"; + return ni.IsComplexInterface + ? ni.ToNoteOutput(nestedIndent, includeDashes, includeBackticks, false) + : RenderProperty(ni, nestedIndent, includeDashes, includeBackticks); + }).Prepend(RenderProperty(complexInterfaceInfo, currentIndent, !isFirst && includeDashes, includeBackticks)); + return String.Join(Environment.NewLine, nested); + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs new file mode 100644 index 00000000000..d40c875615a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/Models/PsProxyTypes.cs @@ -0,0 +1,544 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using System.Reflection; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyOutputExtensions; +using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell.PsProxyTypeExtensions; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal class ProfileGroup + { + public string ProfileName { get; } + public Variant[] Variants { get; } + public string ProfileFolder { get; } + + public ProfileGroup(Variant[] variants, string profileName = NoProfiles) + { + ProfileName = profileName; + Variants = variants; + ProfileFolder = ProfileName != NoProfiles ? ProfileName : String.Empty; + } + } + + internal class VariantGroup + { + public string ModuleName { get; } + + public string RootModuleName { get => @""; } + public string CmdletName { get; } + public string CmdletVerb { get; } + public string CmdletNoun { get; } + public string ProfileName { get; } + public Variant[] Variants { get; } + public ParameterGroup[] ParameterGroups { get; } + public ComplexInterfaceInfo[] ComplexInterfaceInfos { get; } + + public string[] Aliases { get; } + public PSTypeName[] OutputTypes { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + public string DefaultParameterSetName { get; } + public bool HasMultipleVariants { get; } + public PsHelpInfo HelpInfo { get; } + public bool IsGenerated { get; } + public bool IsInternal { get; } + public string OutputFolder { get; } + public string FileName { get; } + public string FilePath { get; } + + public CommentInfo CommentInfo { get; } + + public VariantGroup(string moduleName, string cmdletName, Variant[] variants, string outputFolder, string profileName = NoProfiles, bool isTest = false, bool isInternal = false) + { + ModuleName = moduleName; + CmdletName = cmdletName; + var cmdletNameParts = CmdletName.Split('-'); + CmdletVerb = cmdletNameParts.First(); + CmdletNoun = cmdletNameParts.Last(); + ProfileName = profileName; + Variants = variants; + ParameterGroups = Variants.ToParameterGroups().OrderBy(pg => pg.OrderCategory).ThenByDescending(pg => pg.IsMandatory).ToArray(); + var aliasDuplicates = ParameterGroups.SelectMany(pg => pg.Aliases) + //https://stackoverflow.com/a/18547390/294804 + .GroupBy(a => a).Where(g => g.Count() > 1).Select(g => g.Key).ToArray(); + if (aliasDuplicates.Any()) + { + throw new ParsingMetadataException($"The alias(es) [{String.Join(", ", aliasDuplicates)}] are defined on multiple parameters for cmdlet '{CmdletName}', which is not supported."); + } + ComplexInterfaceInfos = ParameterGroups.Where(pg => !pg.DontShow && pg.IsComplexInterface).OrderBy(pg => pg.ParameterName).Select(pg => pg.ComplexInterfaceInfo).ToArray(); + + Aliases = Variants.SelectMany(v => v.Attributes).ToAliasNames().ToArray(); + OutputTypes = Variants.SelectMany(v => v.Info.OutputType).Where(ot => ot.Type != null).GroupBy(ot => ot.Type).Select(otg => otg.First()).ToArray(); + SupportsShouldProcess = Variants.Any(v => v.SupportsShouldProcess); + SupportsPaging = Variants.Any(v => v.SupportsPaging); + DefaultParameterSetName = DetermineDefaultParameterSetName(); + HasMultipleVariants = Variants.Length > 1; + HelpInfo = Variants.Select(v => v.HelpInfo).FirstOrDefault() ?? new PsHelpInfo(); + IsGenerated = Variants.All(v => v.Attributes.OfType().Any()); + IsInternal = isInternal; + OutputFolder = outputFolder; + FileName = $"{CmdletName}{(isTest ? ".Tests" : String.Empty)}.ps1"; + FilePath = Path.Combine(OutputFolder, FileName); + + CommentInfo = new CommentInfo(this); + } + + private string DetermineDefaultParameterSetName() + { + var defaultParameterSet = Variants + .Select(v => v.Metadata.DefaultParameterSetName) + .LastOrDefault(dpsn => dpsn.IsValidDefaultParameterSetName()); + + if (String.IsNullOrEmpty(defaultParameterSet)) + { + var variantParamCountGroups = Variants + .Where(v => !v.IsNotSuggestDefaultParameterSet) + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + if (variantParamCountGroups.Length == 0) + { + variantParamCountGroups = Variants + .Select(v => ( + variant: v.VariantName, + paramCount: v.CmdletOnlyParameters.Count(p => p.IsMandatory), + isSimple: v.CmdletOnlyParameters.Where(p => p.IsMandatory).All(p => p.ParameterType.IsPsSimple()))) + .GroupBy(vpc => vpc.isSimple) + .ToArray(); + } + var variantParameterCounts = (variantParamCountGroups.Any(g => g.Key) ? variantParamCountGroups.Where(g => g.Key) : variantParamCountGroups).SelectMany(g => g).ToArray(); + var smallestParameterCount = variantParameterCounts.Min(vpc => vpc.paramCount); + defaultParameterSet = variantParameterCounts.First(vpc => vpc.paramCount == smallestParameterCount).variant; + } + + return defaultParameterSet; + } + } + + internal class Variant + { + public string CmdletName { get; } + public string VariantName { get; } + public CommandInfo Info { get; } + public CommandMetadata Metadata { get; } + public PsHelpInfo HelpInfo { get; } + public bool HasParameterSets { get; } + public bool IsFunction { get; } + public string PrivateModuleName { get; } + public string PrivateCmdletName { get; } + public bool SupportsShouldProcess { get; } + public bool SupportsPaging { get; } + + public Attribute[] Attributes { get; } + public Parameter[] Parameters { get; } + public Parameter[] CmdletOnlyParameters { get; } + public bool IsInternal { get; } + public bool IsDoNotExport { get; } + public bool IsNotSuggestDefaultParameterSet { get; } + public string[] Profiles { get; } + + public Variant(string cmdletName, string variantName, CommandInfo info, CommandMetadata metadata, bool hasParameterSets = false, PsHelpInfo helpInfo = null) + { + CmdletName = cmdletName; + VariantName = variantName; + Info = info; + HelpInfo = helpInfo ?? new PsHelpInfo(); + Metadata = metadata; + HasParameterSets = hasParameterSets; + IsFunction = Info.CommandType == CommandTypes.Function; + PrivateModuleName = Info.Source; + PrivateCmdletName = Metadata.Name; + SupportsShouldProcess = Metadata.SupportsShouldProcess; + SupportsPaging = Metadata.SupportsPaging; + + Attributes = this.ToAttributes(); + Parameters = this.ToParameters().OrderBy(p => p.OrderCategory).ThenByDescending(p => p.IsMandatory).ToArray(); + IsInternal = Attributes.OfType().Any(); + IsDoNotExport = Attributes.OfType().Any(); + IsNotSuggestDefaultParameterSet = Attributes.OfType().Any(); + CmdletOnlyParameters = Parameters.Where(p => !p.Categories.Any(c => c == ParameterCategory.Azure || c == ParameterCategory.Runtime)).ToArray(); + Profiles = Attributes.OfType().SelectMany(pa => pa.Profiles).ToArray(); + } + } + + internal class ParameterGroup + { + public string ParameterName { get; } + public Parameter[] Parameters { get; } + + public string[] VariantNames { get; } + public string[] AllVariantNames { get; } + public bool HasAllVariants { get; } + public Type ParameterType { get; } + public string Description { get; } + + public string[] Aliases { get; } + public bool HasValidateNotNull { get; } + public bool HasAllowEmptyArray { get; } + public CompleterInfo CompleterInfo { get; } + public DefaultInfo DefaultInfo { get; } + public bool HasDefaultInfo { get; } + public ParameterCategory OrderCategory { get; } + public bool DontShow { get; } + public bool IsMandatory { get; } + public bool SupportsWildcards { get; } + public bool IsComplexInterface { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public InfoAttribute InfoAttribute { get; } + + public int? FirstPosition { get; } + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public bool IsInputType { get; } + + public ParameterGroup(string parameterName, Parameter[] parameters, string[] allVariantNames) + { + ParameterName = parameterName; + Parameters = parameters; + + VariantNames = Parameters.Select(p => p.VariantName).ToArray(); + AllVariantNames = allVariantNames; + HasAllVariants = VariantNames.Any(vn => vn == AllParameterSets) || !AllVariantNames.Except(VariantNames).Any(); + var types = Parameters.Select(p => p.ParameterType).Distinct().ToArray(); + if (types.Length > 1) + { + throw new ParsingMetadataException($"The parameter '{ParameterName}' has multiple parameter types [{String.Join(", ", types.Select(t => t.Name))}] defined, which is not supported."); + } + ParameterType = types.First(); + Description = Parameters.Select(p => p.Description).FirstOrDefault(d => !String.IsNullOrEmpty(d)).EmptyIfNull(); + + Aliases = Parameters.SelectMany(p => p.Attributes).ToAliasNames().ToArray(); + HasValidateNotNull = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + HasAllowEmptyArray = Parameters.SelectMany(p => p.Attributes.OfType()).Any(); + CompleterInfo = Parameters.Select(p => p.CompleterInfoAttribute).FirstOrDefault()?.ToCompleterInfo() + ?? Parameters.Select(p => p.PSArgumentCompleterAttribute).FirstOrDefault()?.ToPSArgumentCompleterInfo() + ?? Parameters.Select(p => p.ArgumentCompleterAttribute).FirstOrDefault()?.ToCompleterInfo(); + DefaultInfo = Parameters.Select(p => p.DefaultInfoAttribute).FirstOrDefault()?.ToDefaultInfo(this) + ?? Parameters.Select(p => p.DefaultValueAttribute).FirstOrDefault(dv => dv != null)?.ToDefaultInfo(this); + HasDefaultInfo = DefaultInfo != null && !String.IsNullOrEmpty(DefaultInfo.Script); + // When DefaultInfo is present, force all parameters from this group to be optional. + if (HasDefaultInfo) + { + foreach (var parameter in Parameters) + { + parameter.IsMandatory = false; + } + } + OrderCategory = Parameters.Select(p => p.OrderCategory).Distinct().DefaultIfEmpty(ParameterCategory.Body).Min(); + DontShow = Parameters.All(p => p.DontShow); + IsMandatory = HasAllVariants && Parameters.Any(p => p.IsMandatory); + SupportsWildcards = Parameters.Any(p => p.SupportsWildcards); + IsComplexInterface = Parameters.Any(p => p.IsComplexInterface); + ComplexInterfaceInfo = Parameters.Where(p => p.IsComplexInterface).Select(p => p.ComplexInterfaceInfo).FirstOrDefault(); + InfoAttribute = Parameters.Select(p => p.InfoAttribute).First(); + + FirstPosition = Parameters.Select(p => p.Position).FirstOrDefault(p => p != null); + ValueFromPipeline = Parameters.Any(p => p.ValueFromPipeline); + ValueFromPipelineByPropertyName = Parameters.Any(p => p.ValueFromPipelineByPropertyName); + IsInputType = ValueFromPipeline || ValueFromPipelineByPropertyName; + } + } + + internal class Parameter + { + public string VariantName { get; } + public string ParameterName { get; } + public ParameterMetadata Metadata { get; } + public PsParameterHelpInfo HelpInfo { get; } + public Type ParameterType { get; } + public Attribute[] Attributes { get; } + public ParameterCategory[] Categories { get; } + public ParameterCategory OrderCategory { get; } + public PSDefaultValueAttribute DefaultValueAttribute { get; } + public DefaultInfoAttribute DefaultInfoAttribute { get; } + public ParameterAttribute ParameterAttribute { get; } + public bool SupportsWildcards { get; } + public CompleterInfoAttribute CompleterInfoAttribute { get; } + public ArgumentCompleterAttribute ArgumentCompleterAttribute { get; } + public PSArgumentCompleterAttribute PSArgumentCompleterAttribute { get; } + + public bool ValueFromPipeline { get; } + public bool ValueFromPipelineByPropertyName { get; } + public int? Position { get; } + public bool DontShow { get; } + public bool IsMandatory { get; set; } + + public InfoAttribute InfoAttribute { get; } + public ComplexInterfaceInfo ComplexInterfaceInfo { get; } + public bool IsComplexInterface { get; } + public string Description { get; } + + public Parameter(string variantName, string parameterName, ParameterMetadata metadata, PsParameterHelpInfo helpInfo = null) + { + VariantName = variantName; + ParameterName = parameterName; + Metadata = metadata; + HelpInfo = helpInfo ?? new PsParameterHelpInfo(); + + Attributes = Metadata.Attributes.ToArray(); + ParameterType = Attributes.OfType().FirstOrDefault()?.Type ?? Metadata.ParameterType; + Categories = Attributes.OfType().SelectMany(ca => ca.Categories).Distinct().ToArray(); + OrderCategory = Categories.DefaultIfEmpty(ParameterCategory.Body).Min(); + DefaultValueAttribute = Attributes.OfType().FirstOrDefault(); + DefaultInfoAttribute = Attributes.OfType().FirstOrDefault(); + ParameterAttribute = Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == VariantName || pa.ParameterSetName == AllParameterSets); + if (ParameterAttribute == null) + { + throw new ParsingMetadataException($"The variant '{VariantName}' has multiple parameter sets defined, which is not supported."); + } + SupportsWildcards = Attributes.OfType().Any(); + CompleterInfoAttribute = Attributes.OfType().FirstOrDefault(); + PSArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(); + ArgumentCompleterAttribute = Attributes.OfType().FirstOrDefault(attr => !attr.GetType().Equals(typeof(PSArgumentCompleterAttribute))); + + ValueFromPipeline = ParameterAttribute.ValueFromPipeline; + ValueFromPipelineByPropertyName = ParameterAttribute.ValueFromPipelineByPropertyName; + Position = ParameterAttribute.Position == Int32.MinValue ? (int?)null : ParameterAttribute.Position; + DontShow = ParameterAttribute.DontShow; + IsMandatory = ParameterAttribute.Mandatory; + + var complexParameterName = ParameterName.ToUpperInvariant(); + var complexMessage = $"{Environment.NewLine}"; + var description = ParameterAttribute.HelpMessage.NullIfEmpty() ?? HelpInfo.Description.NullIfEmpty() ?? InfoAttribute?.Description.NullIfEmpty() ?? String.Empty; + // Remove the complex type message as it will be reinserted if this is a complex type + description = description.NormalizeNewLines(); + // Make an InfoAttribute for processing only if one isn't provided + InfoAttribute = Attributes.OfType().FirstOrDefault() ?? new InfoAttribute { PossibleTypes = new[] { ParameterType.Unwrap() }, Required = IsMandatory }; + // Set the description if the InfoAttribute does not have one since they are exported without a description + InfoAttribute.Description = String.IsNullOrEmpty(InfoAttribute.Description) ? description : InfoAttribute.Description; + ComplexInterfaceInfo = InfoAttribute.ToComplexInterfaceInfo(complexParameterName, ParameterType, true); + IsComplexInterface = ComplexInterfaceInfo.IsComplexInterface; + Description = $"{description}{(IsComplexInterface ? complexMessage : String.Empty)}"; + } + } + + internal class ComplexInterfaceInfo + { + public InfoAttribute InfoAttribute { get; } + + public string Name { get; } + public Type Type { get; } + public bool Required { get; } + public bool ReadOnly { get; } + public string Description { get; } + + public ComplexInterfaceInfo[] NestedInfos { get; } + public bool IsComplexInterface { get; } + + public ComplexInterfaceInfo(string name, Type type, InfoAttribute infoAttribute, bool? required, List seenTypes) + { + Name = name; + Type = type; + InfoAttribute = infoAttribute; + + Required = required ?? InfoAttribute.Required; + ReadOnly = InfoAttribute.ReadOnly; + Description = InfoAttribute.Description.ToPsSingleLine(); + + var unwrappedType = Type.Unwrap(); + var hasBeenSeen = seenTypes?.Contains(unwrappedType) ?? false; + (seenTypes ?? (seenTypes = new List())).Add(unwrappedType); + NestedInfos = hasBeenSeen ? new ComplexInterfaceInfo[] { } : + unwrappedType.GetInterfaces() + .Concat(InfoAttribute.PossibleTypes) + .SelectMany(pt => pt.GetProperties() + .SelectMany(pi => pi.GetCustomAttributes(true).OfType() + .Select(ia => ia.ToComplexInterfaceInfo(pi.Name, pi.PropertyType, seenTypes: seenTypes)))) + .Where(cii => !cii.ReadOnly).OrderByDescending(cii => cii.Required).ToArray(); + // https://stackoverflow.com/a/503359/294804 + var associativeArrayInnerType = Type.GetInterfaces() + .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAssociativeArray<>)) + ?.GetTypeInfo().GetGenericArguments().First(); + if (!hasBeenSeen && associativeArrayInnerType != null) + { + var anyInfo = new InfoAttribute { Description = "This indicates any property can be added to this object." }; + NestedInfos = NestedInfos.Prepend(anyInfo.ToComplexInterfaceInfo("(Any)", associativeArrayInnerType)).ToArray(); + } + IsComplexInterface = NestedInfos.Any(); + } + } + + internal class CommentInfo + { + public string Description { get; } + public string Synopsis { get; } + + public string[] Examples { get; } + public string[] Inputs { get; } + public string[] Outputs { get; } + + public string OnlineVersion { get; } + public string[] RelatedLinks { get; } + public string[] ExternalUrls { get; } + + private const string HelpLinkPrefix = @"https://learn.microsoft.com/powershell/module/"; + + public CommentInfo(VariantGroup variantGroup) + { + var helpInfo = variantGroup.HelpInfo; + Description = variantGroup.Variants.SelectMany(v => v.Attributes).OfType().FirstOrDefault()?.Description.NullIfEmpty() + ?? helpInfo.Description.EmptyIfNull(); + // If there is no Synopsis, PowerShell may put in the Syntax string as the Synopsis. This seems unintended, so we remove the Synopsis in this situation. + var synopsis = helpInfo.Synopsis.EmptyIfNull().Trim().StartsWith(variantGroup.CmdletName) ? String.Empty : helpInfo.Synopsis; + Synopsis = synopsis.NullIfEmpty() ?? Description; + + Examples = helpInfo.Examples.Select(rl => rl.Code).ToArray(); + + Inputs = (variantGroup.ParameterGroups.Where(pg => pg.IsInputType).Select(pg => pg.ParameterType.FullName).ToArray().NullIfEmpty() ?? + helpInfo.InputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(it => it.Name).ToArray()) + .Where(i => i != "None").Distinct().OrderBy(i => i).ToArray(); + Outputs = (variantGroup.OutputTypes.Select(ot => ot.Type.FullName).ToArray().NullIfEmpty() ?? + helpInfo.OutputTypes.Where(it => it.Name.NullIfWhiteSpace() != null).Select(ot => ot.Name).ToArray()) + .Where(o => o != "None").Distinct().OrderBy(o => o).ToArray(); + + // Use root module name in the help link + var moduleName = variantGroup.RootModuleName == "" ? variantGroup.ModuleName.ToLowerInvariant() : variantGroup.RootModuleName.ToLowerInvariant(); + OnlineVersion = helpInfo.OnlineVersion?.Uri.NullIfEmpty() ?? $@"{HelpLinkPrefix}{moduleName}/{variantGroup.CmdletName.ToLowerInvariant()}"; + RelatedLinks = helpInfo.RelatedLinks.Select(rl => rl.Text).ToArray(); + + // Get external urls from attribute + ExternalUrls = variantGroup.Variants.SelectMany(v => v.Attributes).OfType()?.Select(e => e.Url)?.Distinct()?.ToArray(); + } + } + + internal class CompleterInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public Type Type { get; } + public bool IsTypeCompleter { get; } + + public CompleterInfo(CompleterInfoAttribute infoAttribute) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + } + + public CompleterInfo(ArgumentCompleterAttribute completerAttribute) + { + Script = completerAttribute.ScriptBlock?.ToString(); + if (completerAttribute.Type != null) + { + Type = completerAttribute.Type; + IsTypeCompleter = true; + } + } + } + + internal class PSArgumentCompleterInfo : CompleterInfo + { + public string[] ResourceTypes { get; } + + public PSArgumentCompleterInfo(PSArgumentCompleterAttribute completerAttribute) : base(completerAttribute) + { + ResourceTypes = completerAttribute.ResourceTypes; + } + } + + internal class DefaultInfo + { + public string Name { get; } + public string Description { get; } + public string Script { get; } + public string SetCondition { get; } + public ParameterGroup ParameterGroup { get; } + + public DefaultInfo(DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) + { + Name = infoAttribute.Name; + Description = infoAttribute.Description; + Script = infoAttribute.Script; + SetCondition = infoAttribute.SetCondition; + ParameterGroup = parameterGroup; + } + + public DefaultInfo(PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) + { + Description = defaultValueAttribute.Help; + ParameterGroup = parameterGroup; + if (defaultValueAttribute.Value != null) + { + Script = defaultValueAttribute.Value.ToString(); + } + } + } + + internal static class PsProxyTypeExtensions + { + public const string NoProfiles = "__NoProfiles"; + + public static bool IsValidDefaultParameterSetName(this string parameterSetName) => + !String.IsNullOrEmpty(parameterSetName) && parameterSetName != AllParameterSets; + + public static Variant[] ToVariants(this CommandInfo info, PsHelpInfo helpInfo) + { + var metadata = new CommandMetadata(info); + var privateCmdletName = metadata.Name.Split('!').First(); + var parts = privateCmdletName.Split('_'); + return parts.Length > 1 + ? new[] { new Variant(parts[0], parts[1], info, metadata, helpInfo: helpInfo) } + // Process multiple parameter sets, so we declare a variant per parameter set. + : info.ParameterSets.Select(ps => new Variant(privateCmdletName, ps.Name, info, metadata, true, helpInfo)).ToArray(); + } + + public static Variant[] ToVariants(this CmdletAndHelpInfo info) => info.CommandInfo.ToVariants(info.HelpInfo); + + public static Variant[] ToVariants(this CommandInfo info, PSObject helpInfo = null) => info.ToVariants(helpInfo?.ToPsHelpInfo()); + + public static Parameter[] ToParameters(this Variant variant) + { + var parameters = variant.Metadata.Parameters.AsEnumerable(); + var parameterHelp = variant.HelpInfo.Parameters.AsEnumerable(); + + if (variant.HasParameterSets) + { + parameters = parameters.Where(p => p.Value.ParameterSets.Keys.Any(k => k == variant.VariantName || k == AllParameterSets)); + parameterHelp = parameterHelp.Where(ph => (!ph.ParameterSetNames.Any() || ph.ParameterSetNames.Any(psn => psn == variant.VariantName || psn == AllParameterSets)) && ph.Name != "IncludeTotalCount"); + } + var result = parameters.Select(p => new Parameter(variant.VariantName, p.Key, p.Value, parameterHelp.FirstOrDefault(ph => ph.Name == p.Key))); + if (variant.SupportsPaging) + { + // If supportsPaging is set, we will need to add First and Skip parameters since they are treated as common parameters which as not contained on Metadata>parameters + variant.Info.Parameters["First"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Gets only the first 'n' objects."; + variant.Info.Parameters["Skip"].Attributes.OfType().FirstOrDefault(pa => pa.ParameterSetName == variant.VariantName || pa.ParameterSetName == AllParameterSets).HelpMessage = "Ignores the first 'n' objects and then gets the remaining objects."; + result = result.Append(new Parameter(variant.VariantName, "First", variant.Info.Parameters["First"], parameterHelp.FirstOrDefault(ph => ph.Name == "First"))); + result = result.Append(new Parameter(variant.VariantName, "Skip", variant.Info.Parameters["Skip"], parameterHelp.FirstOrDefault(ph => ph.Name == "Skip"))); + } + return result.ToArray(); + } + + public static Attribute[] ToAttributes(this Variant variant) => variant.IsFunction + ? ((FunctionInfo)variant.Info).ScriptBlock.Attributes.ToArray() + : variant.Metadata.CommandType.GetCustomAttributes(false).Cast().ToArray(); + + public static IEnumerable ToParameterGroups(this Variant[] variants) + { + var allVariantNames = variants.Select(vg => vg.VariantName).ToArray(); + return variants + .SelectMany(v => v.Parameters) + .GroupBy(p => p.ParameterName, StringComparer.InvariantCultureIgnoreCase) + .Select(pg => new ParameterGroup(pg.Key, pg.Select(p => p).ToArray(), allVariantNames)); + } + + public static ComplexInterfaceInfo ToComplexInterfaceInfo(this InfoAttribute infoAttribute, string name, Type type, bool? required = null, List seenTypes = null) + => new ComplexInterfaceInfo(name, type, infoAttribute, required, seenTypes); + + public static CompleterInfo ToCompleterInfo(this CompleterInfoAttribute infoAttribute) => new CompleterInfo(infoAttribute); + public static CompleterInfo ToCompleterInfo(this ArgumentCompleterAttribute completerAttribute) => new CompleterInfo(completerAttribute); + public static PSArgumentCompleterInfo ToPSArgumentCompleterInfo(this PSArgumentCompleterAttribute completerAttribute) => new PSArgumentCompleterInfo(completerAttribute); + public static DefaultInfo ToDefaultInfo(this DefaultInfoAttribute infoAttribute, ParameterGroup parameterGroup) => new DefaultInfo(infoAttribute, parameterGroup); + public static DefaultInfo ToDefaultInfo(this PSDefaultValueAttribute defaultValueAttribute, ParameterGroup parameterGroup) => new DefaultInfo(defaultValueAttribute, parameterGroup); + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsAttributes.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsAttributes.cs new file mode 100644 index 00000000000..fc20bcedc4f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsAttributes.cs @@ -0,0 +1,131 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo +{ + [AttributeUsage(AttributeTargets.Class)] + public class DescriptionAttribute : Attribute + { + public string Description { get; } + + public DescriptionAttribute(string description) + { + Description = description; + } + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class InternalExportAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class GeneratedAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)] + public class DoNotFormatAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Class)] + public class ProfileAttribute : Attribute + { + public string[] Profiles { get; } + + public ProfileAttribute(params string[] profiles) + { + Profiles = profiles; + } + } + + [AttributeUsage(AttributeTargets.Class)] + public class HttpPathAttribute : Attribute + { + public string Path { get; set; } + public string ApiVersion { get; set; } + } + + [AttributeUsage(AttributeTargets.Class)] + public class NotSuggestDefaultParameterSetAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class CategoryAttribute : Attribute + { + public ParameterCategory[] Categories { get; } + + public CategoryAttribute(params ParameterCategory[] categories) + { + Categories = categories; + } + } + + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public class ExportAsAttribute : Attribute + { + public Type Type { get; set; } + + public ExportAsAttribute(Type type) + { + Type = type; + } + } + + public enum ParameterCategory + { + // Note: Order is significant + Uri = 0, + Path, + Query, + Header, + Cookie, + Body, + Azure, + Runtime + } + + [AttributeUsage(AttributeTargets.Property)] + public class OriginAttribute : Attribute + { + public PropertyOrigin Origin { get; } + + public OriginAttribute(PropertyOrigin origin) + { + Origin = origin; + } + } + + public enum PropertyOrigin + { + // Note: Order is significant + Inherited = 0, + Owned, + Inlined + } + + [AttributeUsage(AttributeTargets.Property)] + public class ConstantAttribute : Attribute + { + } + + [AttributeUsage(AttributeTargets.Property)] + public class FormatTableAttribute : Attribute + { + public int Index { get; set; } = -1; + public bool HasIndex => Index != -1; + public string Label { get; set; } + public int Width { get; set; } = -1; + public bool HasWidth => Width != -1; + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsExtensions.cs new file mode 100644 index 00000000000..df78bfec246 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsExtensions.cs @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Management.Automation; +using System.Reflection; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal static class PsExtensions + { + public static PSObject AddMultipleTypeNameIntoPSObject(this object obj, string multipleTag = "#Multiple") + { + var psObj = new PSObject(obj); + psObj.TypeNames.Insert(0, $"{psObj.TypeNames[0]}{multipleTag}"); + return psObj; + } + + // https://stackoverflow.com/a/863944/294804 + // https://stackoverflow.com/a/4452598/294804 + // https://stackoverflow.com/a/28701974/294804 + // Note: This will unwrap nested collections, but we don't generate nested collections. + public static Type Unwrap(this Type type) + { + if (type.IsArray) + { + return type.GetElementType().Unwrap(); + } + + var typeInfo = type.GetTypeInfo(); + if (typeInfo.IsGenericType + && (typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>) || typeof(IEnumerable<>).IsAssignableFrom(type))) + { + return typeInfo.GetGenericArguments().First().Unwrap(); + } + + return type; + } + + // https://stackoverflow.com/a/863944/294804 + private static bool IsSimple(this Type type) + { + var typeInfo = type.GetTypeInfo(); + return typeInfo.IsPrimitive + || typeInfo.IsEnum + || type == typeof(string) + || type == typeof(decimal); + } + + // https://stackoverflow.com/a/32025393/294804 + private static bool HasImplicitConversion(this Type baseType, Type targetType) => + baseType.GetMethods(BindingFlags.Public | BindingFlags.Static) + .Where(mi => mi.Name == "op_Implicit" && mi.ReturnType == targetType) + .Any(mi => mi.GetParameters().FirstOrDefault()?.ParameterType == baseType); + + public static bool IsPsSimple(this Type type) + { + var unwrappedType = type.Unwrap(); + return unwrappedType.IsSimple() + || unwrappedType == typeof(SwitchParameter) + || unwrappedType == typeof(Hashtable) + || unwrappedType == typeof(PSCredential) + || unwrappedType == typeof(ScriptBlock) + || unwrappedType == typeof(DateTime) + || unwrappedType == typeof(Uri) + || unwrappedType.HasImplicitConversion(typeof(string)); + } + + public static string ToPsList(this IEnumerable items) => String.Join(", ", items.Select(i => $"'{i}'")); + + public static IEnumerable ToAliasNames(this IEnumerable attributes) => attributes.OfType().SelectMany(aa => aa.AliasNames).Distinct(); + + public static bool IsArrayAndElementTypeIsT(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return itemType.IsArray && !tType.IsArray && tType.IsAssignableFrom(itemType.GetElementType()); + } + + public static bool IsTArrayAndElementTypeIsItem(this object item) + { + var itemType = item.GetType(); + var tType = typeof(T); + return !itemType.IsArray && tType.IsArray && (tType.GetElementType()?.IsAssignableFrom(itemType) ?? false); + } + + public static bool IsTypeOrArrayOfType(this object item) => item is T || item.IsArrayAndElementTypeIsT() || item.IsTArrayAndElementTypeIsItem(); + + public static T NormalizeArrayType(this object item) + { + if (item is T result) + { + return result; + } + + if (item.IsArrayAndElementTypeIsT()) + { + var array = (T[])Convert.ChangeType(item, typeof(T[])); + return array.FirstOrDefault(); + } + + if (item.IsTArrayAndElementTypeIsItem()) + { + var tType = typeof(T); + var array = Array.CreateInstance(tType.GetElementType(), 1); + array.SetValue(item, 0); + return (T)Convert.ChangeType(array, tType); + } + + return default(T); + } + + public static T GetNestedProperty(this PSObject psObject, params string[] names) => psObject.Properties.GetNestedProperty(names); + + public static T GetNestedProperty(this PSMemberInfoCollection properties, params string[] names) + { + var lastName = names.Last(); + var nestedProperties = names.Take(names.Length - 1).Aggregate(properties, (p, n) => p?.GetProperty(n)?.Properties); + return nestedProperties != null ? nestedProperties.GetProperty(lastName) : default(T); + } + + public static T GetProperty(this PSObject psObject, string name) => psObject.Properties.GetProperty(name); + + public static T GetProperty(this PSMemberInfoCollection properties, string name) + { + switch (properties[name]?.Value) + { + case PSObject psObject when psObject.BaseObject is PSCustomObject && psObject.ImmediateBaseObject.IsTypeOrArrayOfType(): + return psObject.ImmediateBaseObject.NormalizeArrayType(); + case PSObject psObject when psObject.BaseObject.IsTypeOrArrayOfType(): + return psObject.BaseObject.NormalizeArrayType(); + case object value when value.IsTypeOrArrayOfType(): + return value.NormalizeArrayType(); + default: + return default(T); + } + } + + public static IEnumerable RunScript(this PSCmdlet cmdlet, string script) + => PsHelpers.RunScript(cmdlet.InvokeCommand, script); + + public static void RunScript(this PSCmdlet cmdlet, string script) + => cmdlet.RunScript(script); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, string script) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, script); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, string script) + => engineIntrinsics.RunScript(script); + + public static IEnumerable RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => PsHelpers.RunScript(cmdlet.InvokeCommand, block.ToString()); + + public static void RunScript(this PSCmdlet cmdlet, ScriptBlock block) + => cmdlet.RunScript(block.ToString()); + + public static IEnumerable RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => PsHelpers.RunScript(engineIntrinsics.InvokeCommand, block.ToString()); + + public static void RunScript(this EngineIntrinsics engineIntrinsics, ScriptBlock block) + => engineIntrinsics.RunScript(block.ToString()); + + /// + /// Returns if a parameter should be hidden by checking for . + /// + /// A PowerShell parameter. + public static bool IsHidden(this Parameter parameter) + { + return parameter.Attributes.Any(attr => attr is DoNotExportAttribute); + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsHelpers.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsHelpers.cs new file mode 100644 index 00000000000..4f83aa26032 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/PsHelpers.cs @@ -0,0 +1,105 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Management.Automation; +using Pwsh = System.Management.Automation.PowerShell; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal static class PsHelpers + { + public static IEnumerable RunScript(string script) + => Pwsh.Create().AddScript(script).Invoke(); + + public static void RunScript(string script) + => RunScript(script); + + public static IEnumerable RunScript(CommandInvocationIntrinsics cii, string script) + => cii.InvokeScript(script).Select(o => o?.BaseObject).Where(o => o != null).OfType(); + + public static void RunScript(CommandInvocationIntrinsics cii, string script) + => RunScript(cii, script); + + public static IEnumerable GetModuleCmdlets(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletsCommand = String.Join(" + ", modulePaths.Select(mp => $"(Get-Command -Module (Import-Module '{mp}' -PassThru))")); + return (cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand)) + .Where(ci => ci.CommandType != CommandTypes.Alias); + } + + public static IEnumerable GetModuleCmdlets(params string[] modulePaths) + => GetModuleCmdlets(null, modulePaths); + + public static IEnumerable GetScriptCmdlets(PSCmdlet cmdlet, string scriptFolder) + { + // https://stackoverflow.com/a/40969712/294804 + var wrappedFolder = scriptFolder.Contains("'") ? $@"""{scriptFolder}""" : $@"'{scriptFolder}'"; + var getCmdletsCommand = $@" +$currentFunctions = Get-ChildItem function: +Get-ChildItem -Path {wrappedFolder} -Recurse -Include '*.ps1' -File | ForEach-Object {{ . $_.FullName }} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} +"; + return cmdlet?.RunScript(getCmdletsCommand) ?? RunScript(getCmdletsCommand); + } + + public static IEnumerable GetScriptCmdlets(string scriptFolder) + => GetScriptCmdlets(null, scriptFolder); + + public static IEnumerable GetScriptHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var importModules = String.Join(Environment.NewLine, modulePaths.Select(mp => $"Import-Module '{mp}'")); + var getHelpCommand = $@" +$currentFunctions = Get-ChildItem function: +{importModules} +Get-ChildItem function: | Where-Object {{ ($currentFunctions -notcontains $_) -and $_.CmdletBinding }} | ForEach-Object {{ Get-Help -Name $_.Name -Full }} +"; + return cmdlet?.RunScript(getHelpCommand) ?? RunScript(getHelpCommand); + } + + public static IEnumerable GetScriptHelpInfo(params string[] modulePaths) + => GetScriptHelpInfo(null, modulePaths); + + public static IEnumerable GetModuleCmdletsAndHelpInfo(PSCmdlet cmdlet, params string[] modulePaths) + { + var getCmdletAndHelp = String.Join(" + ", modulePaths.Select(mp => + $@"(Get-Command -Module (Import-Module '{mp}' -PassThru) | Where-Object {{ $_.CommandType -ne 'Alias' }} | ForEach-Object {{ @{{ CommandInfo = $_; HelpInfo = ( invoke-command {{ try {{ Get-Help -Name $_.Name -Full }} catch{{ '' }} }} ) }} }})" + )); + return (cmdlet?.RunScript(getCmdletAndHelp) ?? RunScript(getCmdletAndHelp)) + .Select(h => new CmdletAndHelpInfo { CommandInfo = (h["CommandInfo"] as PSObject)?.BaseObject as CommandInfo, HelpInfo = h["HelpInfo"] as PSObject }); + } + + public static IEnumerable GetModuleCmdletsAndHelpInfo(params string[] modulePaths) + => GetModuleCmdletsAndHelpInfo(null, modulePaths); + + public static CmdletAndHelpInfo ToCmdletAndHelpInfo(this CommandInfo commandInfo, PSObject helpInfo) => new CmdletAndHelpInfo { CommandInfo = commandInfo, HelpInfo = helpInfo }; + + public const string Psd1Indent = " "; + public const string GuidStart = Psd1Indent + "GUID"; + + public static Guid ReadGuidFromPsd1(string psd1Path) + { + var guid = Guid.NewGuid(); + if (File.Exists(psd1Path)) + { + var currentGuid = File.ReadAllLines(psd1Path) + .FirstOrDefault(l => l.TrimStart().StartsWith(GuidStart.TrimStart()))?.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries) + .LastOrDefault()?.Replace("'", String.Empty); + guid = currentGuid != null ? Guid.Parse(currentGuid) : guid; + } + + return guid; + } + } + + internal class CmdletAndHelpInfo + { + public CommandInfo CommandInfo { get; set; } + public PSObject HelpInfo { get; set; } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/StringExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/StringExtensions.cs new file mode 100644 index 00000000000..1dfd7d48d3a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/XmlExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/BuildTime/XmlExtensions.cs new file mode 100644 index 00000000000..9ea171405f0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/CmdInfoHandler.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/CmdInfoHandler.cs new file mode 100644 index 00000000000..7e34e2f9dcc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Context.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Context.cs new file mode 100644 index 00000000000..bc8bbff686f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Context.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Extensions; + + /// + /// The IContext Interface defines the communication mechanism for input customization. + /// + /// + /// In the context, we will have client, pipeline, PSBoundParamters, default EventListener, Cancellation. + /// + public interface IContext + { + System.Management.Automation.InvocationInfo InvocationInformation { get; set; } + System.Threading.CancellationTokenSource CancellationTokenSource { get; set; } + System.Collections.Generic.IDictionary ExtensibleParameters { get; } + HttpPipeline Pipeline { get; set; } + Microsoft.Azure.PowerShell.Cmdlets.Qumulo.QumuloStorage Client { get; } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/ConversionException.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/ConversionException.cs new file mode 100644 index 00000000000..b6b6a01e370 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/IJsonConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/IJsonConverter.cs new file mode 100644 index 00000000000..98eeaf1777f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.Json +{ + internal interface IJsonConverter + { + JsonNode ToJson(object value); + + object FromJson(JsonNode node); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/BinaryConverter.cs new file mode 100644 index 00000000000..d2eae451d41 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/BooleanConverter.cs new file mode 100644 index 00000000000..8f8332d52af --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DateTimeConverter.cs new file mode 100644 index 00000000000..e260cee0cdb --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DateTimeOffsetConverter.cs new file mode 100644 index 00000000000..ee5ce7fd18c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DecimalConverter.cs new file mode 100644 index 00000000000..7e0d54c8004 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/DoubleConverter.cs new file mode 100644 index 00000000000..ac0f4f05e87 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/EnumConverter.cs new file mode 100644 index 00000000000..10de2a27718 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/GuidConverter.cs new file mode 100644 index 00000000000..0a5275140f7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/HashSet'1Converter.cs new file mode 100644 index 00000000000..c58c11b7946 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int16Converter.cs new file mode 100644 index 00000000000..01d679c7705 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int32Converter.cs new file mode 100644 index 00000000000..67e0e97f2e7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/Int64Converter.cs new file mode 100644 index 00000000000..2c65aa8bd30 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/JsonArrayConverter.cs new file mode 100644 index 00000000000..03e369ca685 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/JsonObjectConverter.cs new file mode 100644 index 00000000000..c72d076fbc6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/SingleConverter.cs new file mode 100644 index 00000000000..f9f5d285ca2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/StringConverter.cs new file mode 100644 index 00000000000..ae851f9a446 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/TimeSpanConverter.cs new file mode 100644 index 00000000000..2b79caf5402 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt16Converter.cs new file mode 100644 index 00000000000..1fbcc651477 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt32Converter.cs new file mode 100644 index 00000000000..d6677af0700 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UInt64Converter.cs new file mode 100644 index 00000000000..bb85419c068 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/Instances/UriConverter.cs new file mode 100644 index 00000000000..f34d8cb212b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverter.cs new file mode 100644 index 00000000000..57707b0fea8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverterAttribute.cs new file mode 100644 index 00000000000..59cc06a6562 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/JsonConverterFactory.cs new file mode 100644 index 00000000000..f9f441294b2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/StringLikeConverter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Conversions/StringLikeConverter.cs new file mode 100644 index 00000000000..3efb8f683da --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/IJsonSerializable.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/IJsonSerializable.cs new file mode 100644 index 00000000000..954dcb9759b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/IJsonSerializable.cs @@ -0,0 +1,263 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json; +using System; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + public interface IJsonSerializable + { + JsonNode ToJson(JsonObject container = null, SerializationMode serializationMode = SerializationMode.None); + } + internal static class JsonSerializable + { + /// + /// Serializes an enumerable and returns a JsonNode. + /// + /// an IEnumerable collection of items + /// A JsonNode that contains the collection of items serialized. + private static JsonNode ToJsonValue(System.Collections.IEnumerable enumerable) + { + if (enumerable != null) + { + // is it a byte array of some kind? + if (enumerable is System.Collections.Generic.IEnumerable byteEnumerable) + { + return new XBinary(System.Linq.Enumerable.ToArray(byteEnumerable)); + } + + var hasValues = false; + // just create an array of value nodes. + var result = new XNodeArray(); + foreach (var each in enumerable) + { + // we had at least one value. + hasValues = true; + + // try to serialize it. + var node = ToJsonValue(each); + if (null != node) + { + result.Add(node); + } + } + + // if we were able to add values, (or it was just empty), return it. + if (result.Count > 0 || !hasValues) + { + return result; + } + } + + // we couldn't serialize the values. Sorry. + return null; + } + + /// + /// Serializes a valuetype to a JsonNode. + /// + /// a ValueType (ie, a primitive, enum or struct) to be serialized + /// a JsonNode with the serialized value + private static JsonNode ToJsonValue(ValueType vValue) + { + // numeric type + if (vValue is SByte || vValue is Int16 || vValue is Int32 || vValue is Int64 || vValue is Byte || vValue is UInt16 || vValue is UInt32 || vValue is UInt64 || vValue is decimal || vValue is float || vValue is double) + { + return new JsonNumber(vValue.ToString()); + } + + // boolean type + if (vValue is bool bValue) + { + return new JsonBoolean(bValue); + } + + // dates + if (vValue is DateTime dtValue) + { + return new JsonDate(dtValue); + } + + // DictionaryEntity struct type + if (vValue is System.Collections.DictionaryEntry deValue) + { + return new JsonObject { { deValue.Key.ToString(), ToJsonValue(deValue.Value) } }; + } + + // sorry, no idea. + return null; + } + /// + /// Attempts to serialize an object by using ToJson() or ToJsonString() if they exist. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + private static JsonNode TryToJsonValue(dynamic oValue) + { + object jsonValue = null; + dynamic v = oValue; + try + { + jsonValue = v.ToJson().ToString(); + } + catch + { + // no harm... + try + { + jsonValue = v.ToJsonString().ToString(); + } + catch + { + // no worries here either. + } + } + + // if we got something out, let's use it. + if (null != jsonValue) + { + // JsonNumber is really a literal json value. Just don't try to cast that back to an actual number, ok? + return new JsonNumber(jsonValue.ToString()); + } + + return null; + } + + /// + /// Serialize an object by using a variety of methods. + /// + /// the object to be serialized. + /// the serialized JsonNode (if successful), otherwise, null + internal static JsonNode ToJsonValue(object value) + { + // things that implement our interface are preferred. + if (value is Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.JsonSerializable.ToJson(dictionary, null); + } + + // hashtables are converted to dictionaries for serialization + if (value is System.Collections.Hashtable hashtable) + { + var dict = new System.Collections.Generic.Dictionary(); + DictionaryExtensions.HashTableToDictionary(hashtable, dict); + return Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.JsonSerializable.ToJson(dict, null); + } + + // enumerable collections are handled like arrays (again, fallback to ToJson()/ToJsonString() or literal JsonString) + if (value is System.Collections.IEnumerable enumerableValue) + { + // some kind of enumerable value + return ToJsonValue(enumerableValue) ?? TryToJsonValue(value) ?? new JsonString(value.ToString()); + } + + // at this point, we're going to fallback to a string literal here, since we really have no idea what it is. + return new JsonString(value.ToString()); + } + + internal static JsonObject ToJson(System.Collections.Generic.Dictionary dictionary, JsonObject container) => ToJson((System.Collections.Generic.IDictionary)dictionary, container); + + /// + /// Serializes a dictionary into a JsonObject container. + /// + /// The dictionary to serailize + /// the container to serialize the dictionary into + /// the container + internal static JsonObject ToJson(System.Collections.Generic.IDictionary dictionary, JsonObject container) + { + container = container ?? new JsonObject(); + if (dictionary != null && dictionary.Count > 0) + { + foreach (var key in dictionary) + { + // currently, we don't serialize null values. + if (null != key.Value) + { + container.Add(key.Key, ToJsonValue(key.Value)); + continue; + } + } + } + return container; + } + + internal static Func> DeserializeDictionary(Func> dictionaryFactory) + { + return (node) => FromJson(node, dictionaryFactory(), (object)(DeserializeDictionary(dictionaryFactory)) as Func); + } + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.Dictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) => FromJson(json, (System.Collections.Generic.IDictionary)container, objectFactory, excludes); + + + internal static System.Collections.Generic.IDictionary FromJson(JsonObject json, System.Collections.Generic.IDictionary container, System.Func objectFactory, System.Collections.Generic.HashSet excludes = null) + { + if (null == json) + { + return container; + } + + foreach (var key in json.Keys) + { + if (true == excludes?.Contains(key)) + { + continue; + } + + var value = json[key]; + try + { + switch (value.Type) + { + case JsonType.Null: + // skip null values. + continue; + + case JsonType.Array: + case JsonType.Boolean: + case JsonType.Date: + case JsonType.Binary: + case JsonType.Number: + case JsonType.String: + container.Add(key, (V)value.ToValue()); + break; + case JsonType.Object: + if (objectFactory != null) + { + var v = objectFactory(value as JsonObject); + if (null != v) + { + container.Add(key, v); + } + } + break; + } + } + catch + { + } + } + return container; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonArray.cs new file mode 100644 index 00000000000..7462a8f1c4d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonBoolean.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonBoolean.cs new file mode 100644 index 00000000000..66955b868ad --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonNode.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonNode.cs new file mode 100644 index 00000000000..c826364f5f2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonNumber.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonNumber.cs new file mode 100644 index 00000000000..64fd0add5aa --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonObject.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonObject.cs new file mode 100644 index 00000000000..7d248b130b6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.Json +{ + using System; + using System.Collections.Generic; + + public partial class JsonObject + { + internal override object ToValue() => Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonString.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/JsonString.cs new file mode 100644 index 00000000000..affe53b2a6d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/XNodeArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Customizations/XNodeArray.cs new file mode 100644 index 00000000000..3d7f6ae895f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Debugging.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Debugging.cs new file mode 100644 index 00000000000..46a8a19f169 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/DictionaryExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/DictionaryExtensions.cs new file mode 100644 index 00000000000..1e111c94c72 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/DictionaryExtensions.cs @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + internal static class DictionaryExtensions + { + internal static void HashTableToDictionary(System.Collections.Hashtable hashtable, System.Collections.Generic.IDictionary dictionary) + { + if (null == hashtable) + { + return; + } + foreach (var each in hashtable.Keys) + { + var key = each.ToString(); + var value = hashtable[key]; + if (null != value) + { + try + { + dictionary[key] = (V)value; + } + catch + { + // Values getting dropped; not compatible with target dictionary. Not sure what to do here. + } + } + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventData.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventData.cs new file mode 100644 index 00000000000..a5d2857b3b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventDataExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventDataExtensions.cs new file mode 100644 index 00000000000..9a2508cf172 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime +{ + using System; + + /// + /// PowerShell-specific data on top of the llc# EventData + /// + /// + /// In PowerShell, we add on the EventDataConverter to support sending events between modules. + /// Obviously, this code would need to be duplcated on both modules. + /// This is preferable to sharing a common library, as versioning makes that problematic. + /// + [System.ComponentModel.TypeConverter(typeof(EventDataConverter))] + public partial class EventData : EventArgs + { + } + + /// + /// A PowerShell PSTypeConverter to adapt an EventData object that has been passed. + /// Usually used between modules. + /// + public class EventDataConverter : System.Management.Automation.PSTypeConverter + { + public override bool CanConvertTo(object sourceValue, Type destinationType) => false; + public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null; + public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue); + public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); + + /// + /// Verifies that a given object has the required members to convert it to the target type (EventData) + /// + /// Uses a dynamic type so that it is able to use the simplest code without excessive checking. + /// + /// The instance to verify + /// True, if the object has all the required parameters. + public static bool CanConvertFrom(dynamic sourceValue) + { + try + { + // check if this has *required* parameters... + sourceValue?.Id?.GetType(); + sourceValue?.Message?.GetType(); + sourceValue?.Cancel?.GetType(); + + // remaining parameters are not *required*, + // and if they have values, it will copy them at conversion time. + } + catch + { + // if anything throws an exception (because it's null, or doesn't have that member) + return false; + } + return true; + } + + /// + /// Returns result of the delegate as the expected type, or default(T) + /// + /// This isolates any exceptions from the consumer. + /// + /// A delegate that returns a value + /// The desired output type + /// The value from the function if the type is correct + private static T To(Func srcValue) + { + try { return srcValue(); } + catch { return default(T); } + } + + /// + /// Converts an incoming object to the expected type by treating the incoming object as a dynamic, and coping the expected values. + /// + /// the incoming object + /// EventData + public static EventData ConvertFrom(dynamic sourceValue) + { + return new EventData + { + Id = To(() => sourceValue.Id), + Message = To(() => sourceValue.Message), + Parameter = To(() => sourceValue.Parameter), + Value = To(() => sourceValue.Value), + RequestMessage = To(() => sourceValue.RequestMessage), + ResponseMessage = To(() => sourceValue.ResponseMessage), + Cancel = To(() => sourceValue.Cancel) + }; + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventListener.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventListener.cs new file mode 100644 index 00000000000..d4bce219afb --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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.Qumulo.Runtime.Extensions; + + public interface IValidates + { + Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Events.ValidationWarning, instance.Token, () => new EventData { Id = Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Events.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Events.cs new file mode 100644 index 00000000000..ea95a9246d3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime +{ + public static partial class Events + { + public const string Log = nameof(Log); + public const string Validation = nameof(Validation); + public const string ValidationWarning = nameof(ValidationWarning); + public const string AfterValidation = nameof(AfterValidation); + public const string RequestCreated = nameof(RequestCreated); + public const string ResponseCreated = nameof(ResponseCreated); + public const string URLCreated = nameof(URLCreated); + public const string Finally = nameof(Finally); + public const string HeaderParametersAdded = nameof(HeaderParametersAdded); + public const string BodyContentSet = nameof(BodyContentSet); + public const string BeforeCall = nameof(BeforeCall); + public const string BeforeResponseDispatch = nameof(BeforeResponseDispatch); + public const string FollowingNextLink = nameof(FollowingNextLink); + public const string DelayBeforePolling = nameof(DelayBeforePolling); + public const string Polling = nameof(Polling); + public const string Progress = nameof(Progress); + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventsExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/EventsExtensions.cs new file mode 100644 index 00000000000..0deaf7d14e6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Extensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Extensions.cs new file mode 100644 index 00000000000..64c02029d34 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Extensions.cs @@ -0,0 +1,117 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using System.Linq; + using System; + + internal static partial class Extensions + { + public static T[] SubArray(this T[] array, int offset, int length) + { + return new ArraySegment(array, offset, length) + .ToArray(); + } + + public static T ReadHeaders(this T instance, global::System.Net.Http.Headers.HttpResponseHeaders headers) where T : class + { + (instance as IHeaderSerializable)?.ReadHeaders(headers); + return instance; + } + + internal static bool If(T input, out T output) + { + if (null == input) + { + output = default(T); + return false; + } + output = input; + return true; + } + + internal static void AddIf(T value, System.Action addMethod) + { + // if value is present (and it's not just an empty JSON Object) + if (null != value && (value as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonObject)?.Keys.Count != 0) + { + addMethod(serializedName, value); + } + } + + /// + /// Returns the first header value as a string from an HttpReponseMessage. + /// + /// the HttpResponseMessage to fetch a header from + /// the header name + /// the first header value as a string from an HttpReponseMessage. string.empty if there is no header value matching + internal static string GetFirstHeader(this System.Net.Http.HttpResponseMessage response, string headerName) => response.Headers.FirstOrDefault(each => string.Equals(headerName, each.Key, System.StringComparison.OrdinalIgnoreCase)).Value?.FirstOrDefault() ?? string.Empty; + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchonization context to the original value. + /// + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static System.IDisposable NoSynchronizationContext => System.Threading.SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + + /// + /// An instance of the Dummy IDispoable. + /// + /// + internal static System.IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : System.IDisposable + { + public void Dispose() + { + } + } + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : System.IDisposable + { + private System.Threading.SynchronizationContext original = System.Threading.SynchronizationContext.Current; + internal NoSyncContext() + { + System.Threading.SynchronizationContext.SetSynchronizationContext(null); + } + public void Dispose() => System.Threading.SynchronizationContext.SetSynchronizationContext(original); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Extensions/StringBuilderExtensions.cs new file mode 100644 index 00000000000..32147cddb36 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Extensions/TypeExtensions.cs new file mode 100644 index 00000000000..81013c9dad8 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Seperator.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/Seperator.cs new file mode 100644 index 00000000000..a3239222e3c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.Json +{ + internal static class Seperator + { + internal static readonly char[] Dash = { '-' }; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/TypeDetails.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/TypeDetails.cs new file mode 100644 index 00000000000..5a9e5340b0c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/XHelper.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Helpers/XHelper.cs new file mode 100644 index 00000000000..7a20146a117 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/HttpPipeline.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/HttpPipeline.cs new file mode 100644 index 00000000000..18cf46edbc0 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/HttpPipelineMocking.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/HttpPipelineMocking.ps1 new file mode 100644 index 00000000000..65d000098c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/IAssociativeArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/IAssociativeArray.cs new file mode 100644 index 00000000000..a0bc3b78555 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/IAssociativeArray.cs @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +#define DICT_PROPERTIES +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + /// A subset of IDictionary that doesn't implement IEnumerable or IDictionary to work around PowerShell's aggressive formatter + public interface IAssociativeArray + { +#if DICT_PROPERTIES + System.Collections.Generic.IEnumerable Keys { get; } + System.Collections.Generic.IEnumerable Values { get; } + int Count { get; } +#endif + System.Collections.Generic.IDictionary AdditionalProperties { get; } + T this[string index] { get; set; } + void Add(string key, T value); + bool ContainsKey(string key); + bool Remove(string key); + bool TryGetValue(string key, out T value); + void Clear(); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/IHeaderSerializable.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/IHeaderSerializable.cs new file mode 100644 index 00000000000..d4d16c16267 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime +{ + public interface IHeaderSerializable + { + void ReadHeaders(global::System.Net.Http.Headers.HttpResponseHeaders headers); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/ISendAsync.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/ISendAsync.cs new file mode 100644 index 00000000000..8e651737255 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/ISendAsync.cs @@ -0,0 +1,413 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using System.Net.Http; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using System.Collections; + using System.Linq; + using System; + + + /// + /// The interface for sending an HTTP request across the wire. + /// + public interface ISendAsync + { + Task SendAsync(HttpRequestMessage request, IEventListener callback); + } + + public class SendAsyncTerminalFactory : ISendAsyncTerminalFactory, ISendAsync + { + SendAsync implementation; + + public SendAsyncTerminalFactory(SendAsync implementation) => this.implementation = implementation; + public SendAsyncTerminalFactory(ISendAsync implementation) => this.implementation = implementation.SendAsync; + public ISendAsync Create() => this; + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback); + } + + public partial class SendAsyncFactory : ISendAsyncFactory + { + public class Sender : ISendAsync + { + internal ISendAsync next; + internal SendAsyncStep implementation; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => implementation(request, callback, next); + } + SendAsyncStep implementation; + + public SendAsyncFactory(SendAsyncStep implementation) => this.implementation = implementation; + public ISendAsync Create(ISendAsync next) => new Sender { next = next, implementation = implementation }; + + } + + public class HttpClientFactory : ISendAsyncTerminalFactory, ISendAsync + { + HttpClient client; + public HttpClientFactory() : this(new HttpClient()) + { + } + public HttpClientFactory(HttpClient client) => this.client = client; + public ISendAsync Create() => this; + + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, callback.Token); + } + + public interface ISendAsyncFactory + { + ISendAsync Create(ISendAsync next); + } + + public interface ISendAsyncTerminalFactory + { + ISendAsync Create(); + } + + public partial class HttpPipeline : ISendAsync + { + private const int DefaultMaxRetry = 3; + private ISendAsync pipeline; + private ISendAsyncTerminalFactory terminal; + private List steps = new List(); + + public HttpPipeline() : this(new HttpClientFactory()) + { + } + + public HttpPipeline(ISendAsyncTerminalFactory terminalStep) + { + if (terminalStep == null) + { + throw new System.ArgumentNullException(nameof(terminalStep), "Terminal Step Factory in HttpPipeline may not be null"); + } + TerminalFactory = terminalStep; + } + + /// + /// Returns an HttpPipeline with the current state of this pipeline. + /// + public HttpPipeline Clone() => new HttpPipeline(terminal) { steps = this.steps.ToList(), pipeline = this.pipeline }; + + private bool shouldRetry429(HttpResponseMessage response) + { + if (response.StatusCode == (System.Net.HttpStatusCode)429) + { + var retryAfter = response.Headers.RetryAfter; + if (retryAfter != null && retryAfter.Delta.HasValue) + { + return true; + } + } + return false; + } + /// + /// The step to handle 429 response with retry-after header. + /// + public async Task Retry429(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = int.MaxValue; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES_FOR_429")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES_FOR_429")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetry429(response) && count++ < retryCount) + { + request = await cloneRequest.CloneWithContent(); + var retryAfter = response.Headers.RetryAfter; + await Task.Delay(retryAfter.Delta.Value, callback.Token); + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code 429 after waiting {retryAfter.Delta.Value.TotalSeconds} seconds."); + response = await next.SendAsync(request, callback); + } + return response; + } + + private bool shouldRetryError(HttpResponseMessage response) + { + if (response.StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + if (response.StatusCode != System.Net.HttpStatusCode.NotImplemented && + response.StatusCode != System.Net.HttpStatusCode.HttpVersionNotSupported) + { + return true; + } + } + else if (response.StatusCode == System.Net.HttpStatusCode.RequestTimeout) + { + return true; + } + else if (response.StatusCode == (System.Net.HttpStatusCode)429 && response.Headers.RetryAfter == null) + { + return true; + } + return false; + } + + /// + /// Returns true if status code in HttpRequestExceptionWithStatus exception is greater + /// than or equal to 500 and not NotImplemented (501) or HttpVersionNotSupported (505). + /// Or it's 429 (TOO MANY REQUESTS) without Retry-After header. + /// + public async Task RetryError(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + int retryCount = DefaultMaxRetry; + + try + { + try + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("PS_HTTP_MAX_RETRIES")); + } + finally + { + retryCount = int.Parse(System.Environment.GetEnvironmentVariable("AZURE_PS_HTTP_MAX_RETRIES")); + } + } + catch (System.Exception) + { + //no action + } + var cloneRequest = await request.CloneWithContent(); + var response = await next.SendAsync(request, callback); + int count = 0; + while (shouldRetryError(response) && count++ < retryCount) + { + await callback.Signal("Debug", $"Start to retry {count} time(s) on status code {response.StatusCode}"); + request = await cloneRequest.CloneWithContent(); + response = await next.SendAsync(request, callback); + } + return response; + } + + public ISendAsyncTerminalFactory TerminalFactory + { + get => terminal; + set + { + if (value == null) + { + throw new System.ArgumentNullException("TerminalFactory in HttpPipeline may not be null"); + } + terminal = value; + } + } + + public ISendAsync Pipeline + { + get + { + // if the pipeline has been created and not invalidated, return it. + if (this.pipeline != null) + { + return this.pipeline; + } + + // create the pipeline from scratch. + var next = terminal.Create(); + if (Convert.ToBoolean(@"true")) + { + next = (new SendAsyncFactory(Retry429)).Create(next) ?? next; + next = (new SendAsyncFactory(RetryError)).Create(next) ?? next; + } + foreach (var factory in steps) + { + // skip factories that return null. + next = factory.Create(next) ?? next; + } + return this.pipeline = next; + } + } + + public int Count => steps.Count; + + public HttpPipeline Prepend(ISendAsyncFactory item) + { + if (item != null) + { + steps.Add(item); + pipeline = null; + } + return this; + } + + public HttpPipeline Append(SendAsyncStep item) + { + if (item != null) + { + Append(new SendAsyncFactory(item)); + } + return this; + } + + public HttpPipeline Prepend(SendAsyncStep item) + { + if (item != null) + { + Prepend(new SendAsyncFactory(item)); + } + return this; + } + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(new SendAsyncFactory(item)); + } + } + return this; + } + + public HttpPipeline Append(ISendAsyncFactory item) + { + if (item != null) + { + steps.Insert(0, item); + pipeline = null; + } + return this; + } + public HttpPipeline Prepend(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Prepend(item); + } + } + return this; + } + + public HttpPipeline Append(IEnumerable items) + { + if (items != null) + { + foreach (var item in items) + { + Append(item); + } + } + return this; + } + + // you can use this as the ISendAsync Implementation + public Task SendAsync(HttpRequestMessage request, IEventListener callback) => Pipeline.SendAsync(request, callback); + } + + internal static partial class Extensions + { + internal static HttpRequestMessage CloneAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.Clone(requestUri, method); + } + } + + internal static Task CloneWithContentAndDispose(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + using (original) + { + return original.CloneWithContent(requestUri, method); + } + } + + /// + /// Clones an HttpRequestMessage (without the content) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static HttpRequestMessage Clone(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = new HttpRequestMessage + { + Method = method ?? original.Method, + RequestUri = requestUri ?? original.RequestUri, + Version = original.Version, + }; + + foreach (KeyValuePair prop in original.Properties) + { + clone.Properties.Add(prop); + } + + foreach (KeyValuePair> header in original.Headers) + { + /* + **temporarily skip cloning telemetry related headers** + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + */ + if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key)) + { + clone.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + } + + return clone; + } + + /// + /// Clones an HttpRequestMessage (including the content stream and content headers) + /// + /// Original HttpRequestMessage (Will be diposed before returning) + /// + /// + /// A clone of the HttpRequestMessage + internal static async Task CloneWithContent(this HttpRequestMessage original, System.Uri requestUri = null, System.Net.Http.HttpMethod method = null) + { + var clone = original.Clone(requestUri, method); + var stream = new System.IO.MemoryStream(); + if (original.Content != null) + { + await original.Content.CopyToAsync(stream).ConfigureAwait(false); + stream.Position = 0; + clone.Content = new StreamContent(stream); + if (original.Content.Headers != null) + { + foreach (var h in original.Content.Headers) + { + clone.Content.Headers.Add(h.Key, h.Value); + } + } + } + return clone; + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InfoAttribute.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InfoAttribute.cs new file mode 100644 index 00000000000..5eeba33b4d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InfoAttribute.cs @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using System; + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Class)] + public class InfoAttribute : Attribute + { + public bool Required { get; set; } = false; + public bool ReadOnly { get; set; } = false; + public bool Read { get; set; } = true; + public bool Create { get; set; } = true; + public bool Update { get; set; } = true; + public Type[] PossibleTypes { get; set; } = new Type[0]; + public string Description { get; set; } = ""; + public string SerializedName { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class CompleterInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class DefaultInfoAttribute : Attribute + { + public string Script { get; set; } = ""; + public string Name { get; set; } = ""; + public string Description { get; set; } = ""; + public string SetCondition { get; set; } = ""; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InputHandler.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InputHandler.cs new file mode 100644 index 00000000000..36065810677 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/InputHandler.cs @@ -0,0 +1,22 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Cmdlets +{ + public abstract class InputHandler + { + protected InputHandler NextHandler = null; + + public void SetNextHandler(InputHandler nextHandler) + { + this.NextHandler = nextHandler; + } + + public abstract void Process(Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.IContext context); + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Iso/IsoDate.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Iso/IsoDate.cs new file mode 100644 index 00000000000..c9968e29018 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/JsonType.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/JsonType.cs new file mode 100644 index 00000000000..392cea835d2 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttribute.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttribute.cs new file mode 100644 index 00000000000..2d90694bdc9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttribute.cs @@ -0,0 +1,350 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + using System.Text; + + [AttributeUsage(AttributeTargets.All)] + public class GenericBreakingChangeAttribute : Attribute + { + private string _message; + //A dexcription of what the change is about, non mandatory + public string ChangeDescription { get; set; } = null; + + //The version the change is effective from, non mandatory + public string DeprecateByVersion { get; } + public string DeprecateByAzVersion { get; } + + //The date on which the change comes in effect + public DateTime ChangeInEfectByDate { get; } + public bool ChangeInEfectByDateSet { get; } = false; + + //Old way of calling the cmdlet + public string OldWay { get; set; } + //New way fo calling the cmdlet + public string NewWay { get; set; } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion) + { + _message = message; + this.DeprecateByAzVersion = deprecateByAzVersion; + this.DeprecateByVersion = deprecateByVersion; + } + + public GenericBreakingChangeAttribute(string message, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) + { + _message = message; + this.DeprecateByVersion = deprecateByVersion; + this.DeprecateByAzVersion = deprecateByAzVersion; + + if (DateTime.TryParse(changeInEfectByDate, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.ChangeInEfectByDate = result; + this.ChangeInEfectByDateSet = true; + } + } + + public DateTime getInEffectByDate() + { + return this.ChangeInEfectByDate.Date; + } + + + /** + * This function prints out the breaking change message for the attribute on the cmdline + * */ + public void PrintCustomAttributeInfo(Action writeOutput) + { + + if (!GetAttributeSpecificMessage().StartsWith(Environment.NewLine)) + { + writeOutput(Environment.NewLine); + } + writeOutput(string.Format(Resources.BreakingChangesAttributesDeclarationMessage, GetAttributeSpecificMessage())); + + + if (!string.IsNullOrWhiteSpace(ChangeDescription)) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesChangeDescriptionMessage, this.ChangeDescription)); + } + + if (ChangeInEfectByDateSet) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByDateMessage, this.ChangeInEfectByDate.ToString("d"))); + } + + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByAzVersion, this.DeprecateByAzVersion)); + writeOutput(string.Format(Resources.BreakingChangesAttributesInEffectByVersion, this.DeprecateByVersion)); + + if (OldWay != null && NewWay != null) + { + writeOutput(string.Format(Resources.BreakingChangesAttributesUsageChangeMessageConsole, OldWay, NewWay)); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + + protected virtual string GetAttributeSpecificMessage() + { + return _message; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class CmdletBreakingChangeAttribute : GenericBreakingChangeAttribute + { + + public string ReplacementCmdletName { get; set; } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + } + + public CmdletBreakingChangeAttribute(string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + } + + protected override string GetAttributeSpecificMessage() + { + if (string.IsNullOrWhiteSpace(ReplacementCmdletName)) + { + return Resources.BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement; + } + else + { + return string.Format(Resources.BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement, ReplacementCmdletName); + } + } + } + + [AttributeUsage(AttributeTargets.All)] + public class ParameterSetBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string[] ChangedParameterSet { set; get; } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + ChangedParameterSet = changedParameterSet; + } + + public ParameterSetBreakingChangeAttribute(string[] changedParameterSet, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + ChangedParameterSet = changedParameterSet; + } + + protected override string GetAttributeSpecificMessage() + { + + return Resources.BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement; + + } + + public bool IsApplicableToInvocation(InvocationInfo invocation, string parameterSetName) + { + if (ChangedParameterSet != null) + return ChangedParameterSet.Contains(parameterSetName); + return false; + } + + } + + [AttributeUsage(AttributeTargets.All)] + public class PreviewMessageAttribute : Attribute + { + public string _message; + + public DateTime EstimatedGaDate { get; } + + public bool IsEstimatedGaDateSet { get; } = false; + + + public PreviewMessageAttribute() + { + this._message = Resources.PreviewCmdletMessage; + } + + public PreviewMessageAttribute(string message) + { + this._message = string.IsNullOrEmpty(message) ? Resources.PreviewCmdletMessage : message; + } + + public PreviewMessageAttribute(string message, string estimatedDateOfGa) : this(message) + { + if (DateTime.TryParse(estimatedDateOfGa, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime result)) + { + this.EstimatedGaDate = result; + this.IsEstimatedGaDateSet = true; + } + } + + public void PrintCustomAttributeInfo(Action writeOutput) + { + writeOutput(this._message); + + if (IsEstimatedGaDateSet) + { + writeOutput(string.Format(Resources.PreviewCmdletETAMessage, this.EstimatedGaDate.ToShortDateString())); + } + } + + public virtual bool IsApplicableToInvocation(InvocationInfo invocation) + { + return true; + } + } + + [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] + public class ParameterBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string NameOfParameterChanging { get; } + + public string ReplaceMentCmdletParameterName { get; set; } = null; + + public bool IsBecomingMandatory { get; set; } = false; + + public String OldParamaterType { get; set; } + + public String NewParameterType { get; set; } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + public ParameterBreakingChangeAttribute(string nameOfParameterChanging, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.NameOfParameterChanging = nameOfParameterChanging; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + if (!string.IsNullOrWhiteSpace(ReplaceMentCmdletParameterName)) + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplacedMandatory, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterReplaced, NameOfParameterChanging, ReplaceMentCmdletParameterName)); + } + } + else + { + if (IsBecomingMandatory) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterMandatoryNow, NameOfParameterChanging)); + } + else + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterChanging, NameOfParameterChanging)); + } + } + + //See if the type of the param is changing + if (OldParamaterType != null && !string.IsNullOrWhiteSpace(NewParameterType)) + { + message.Append(string.Format(Resources.BreakingChangeAttributeParameterTypeChange, OldParamaterType, NewParameterType)); + } + return message.ToString(); + } + + /// + /// See if the bound parameters contain the current parameter, if they do + /// then the attribbute is applicable + /// If the invocationInfo is null we return true + /// + /// + /// bool + public override bool IsApplicableToInvocation(InvocationInfo invocationInfo) + { + bool? applicable = invocationInfo == null ? true : invocationInfo.BoundParameters?.Keys?.Contains(this.NameOfParameterChanging); + return applicable.HasValue ? applicable.Value : false; + } + } + + [AttributeUsage(AttributeTargets.All)] + public class OutputBreakingChangeAttribute : GenericBreakingChangeAttribute + { + public string DeprecatedCmdLetOutputType { get; } + + //This is still a String instead of a Type as this + //might be undefined at the time of adding the attribute + public string ReplacementCmdletOutputType { get; set; } + + public string[] DeprecatedOutputProperties { get; set; } + + public string[] NewOutputProperties { get; set; } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + public OutputBreakingChangeAttribute(string deprecatedCmdletOutputType, string deprecateByAzVersion, string deprecateByVersion, string changeInEfectByDate) : + base(string.Empty, deprecateByAzVersion, deprecateByVersion, changeInEfectByDate) + { + this.DeprecatedCmdLetOutputType = deprecatedCmdletOutputType; + } + + protected override string GetAttributeSpecificMessage() + { + StringBuilder message = new StringBuilder(); + + //check for the deprecation scenario + if (string.IsNullOrWhiteSpace(ReplacementCmdletOutputType) && NewOutputProperties == null && DeprecatedOutputProperties == null && string.IsNullOrWhiteSpace(ChangeDescription)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputTypeDeprecated, DeprecatedCmdLetOutputType)); + } + else + { + if (!string.IsNullOrWhiteSpace(ReplacementCmdletOutputType)) + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange1, DeprecatedCmdLetOutputType, ReplacementCmdletOutputType)); + } + else + { + message.Append(string.Format(Resources.BreakingChangesAttributesCmdLetOutputChange2, DeprecatedCmdLetOutputType)); + } + + if (DeprecatedOutputProperties != null && DeprecatedOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesRemoved); + foreach (string property in DeprecatedOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + + if (NewOutputProperties != null && NewOutputProperties.Length > 0) + { + message.Append(Resources.BreakingChangesAttributesCmdLetOutputPropertiesAdded); + foreach (string property in NewOutputProperties) + { + message.Append(" '" + property + "'"); + } + } + } + return message.ToString(); + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttributeHelper.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttributeHelper.cs new file mode 100644 index 00000000000..b4fed23eba7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/MessageAttributeHelper.cs @@ -0,0 +1,184 @@ +// ---------------------------------------------------------------------------------- +// +// Copyright Microsoft Corporation +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// ---------------------------------------------------------------------------------- +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.generated.runtime.Properties; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Management.Automation; + using System.Reflection; + using System.Text; + using System.Threading.Tasks; + public class MessageAttributeHelper + { + private static readonly bool IsAzure = Convert.ToBoolean(@"true"); + public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; + public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And reads all the deprecation attributes attached to it + * Prints a message on the cmdline For each of the attribute found + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + * */ + public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet, bool showPreviewMessage = true) + { + bool supressWarningOrError = false; + + try + { + supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); + } + catch (Exception) + { + //no action + } + + if (supressWarningOrError) + { + //Do not process the attributes at runtime... The env variable to override the warning messages is set + return; + } + if (IsAzure && invocationInfo.BoundParameters.ContainsKey("DefaultProfile")) + { + psCmdlet.WriteWarning("The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription."); + } + + ProcessBreakingChangeAttributesAtRuntime(commandInfo, invocationInfo, parameterSet, psCmdlet); + + } + + private static void ProcessBreakingChangeAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List attributes = new List(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (attributes != null && attributes.Count > 0) + { + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); + + foreach (GenericBreakingChangeAttribute attribute in attributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + + appendAttributeMessage(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); + + psCmdlet.WriteWarning(sb.ToString()); + } + } + + + public static void ProcessPreviewMessageAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) + { + List previewAttributes = new List(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); + StringBuilder sb = new StringBuilder(); + Action appendAttributeMessage = (string s) => sb.Append(s); + + if (previewAttributes != null && previewAttributes.Count > 0) + { + foreach (PreviewMessageAttribute attribute in previewAttributes) + { + attribute.PrintCustomAttributeInfo(appendAttributeMessage); + } + psCmdlet.WriteWarning(sb.ToString()); + } + } + + /** + * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) + * And returns all the deprecation attributes attached to it + * + * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, + * We only process the Parameter beaking change attributes attached only params listed in this list (if present) + **/ + private static IEnumerable GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) + { + List attributeList = new List(); + + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); + } + + public static bool ContainsPreviewAttribute(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + return GetAllPreviewAttributesInType(commandInfo, invocationInfo)?.Count() > 0; + } + + private static IEnumerable GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) + { + List attributeList = new List(); + if (commandInfo.GetType() == typeof(CmdletInfo)) + { + var type = ((CmdletInfo)commandInfo).ImplementingType; + attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + + foreach (MethodInfo m in type.GetRuntimeMethods()) + { + attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast())); + } + + foreach (FieldInfo f in type.GetRuntimeFields()) + { + attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + + foreach (PropertyInfo p in type.GetRuntimeProperties()) + { + attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast()); + } + } + else if (commandInfo.GetType() == typeof(FunctionInfo)) + { + attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) + { + attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast()); + } + } + return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Method.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Method.cs new file mode 100644 index 00000000000..cbcb76a6421 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonMember.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonMember.cs new file mode 100644 index 00000000000..48b6cf3191f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonModel.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonModel.cs new file mode 100644 index 00000000000..29e020dbf44 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonModelCache.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Models/JsonModelCache.cs new file mode 100644 index 00000000000..e5ed6a0a55d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/JsonArray.cs new file mode 100644 index 00000000000..0ad39b70a61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XImmutableArray.cs new file mode 100644 index 00000000000..c2a17fabdd9 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XList.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XList.cs new file mode 100644 index 00000000000..60cf95f2df6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs new file mode 100644 index 00000000000..3823747ef6c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XNodeArray.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.Collections; +using System.Collections.Generic; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json +{ + public sealed partial class XNodeArray : JsonArray, ICollection + { + private readonly List items; + + internal XNodeArray() + { + items = new List(); + } + + internal XNodeArray(params JsonNode[] values) + { + items = new List(values); + } + + internal XNodeArray(System.Collections.Generic.List values) + { + items = new List(values); + } + + public override JsonNode this[int index] => items[index]; + + internal override JsonType? ElementType => null; + + public bool IsReadOnly => false; + + public override int Count => items.Count; + + #region ICollection Members + + public void Add(JsonNode item) + { + items.Add(item); + } + + void ICollection.Clear() + { + items.Clear(); + } + + public bool Contains(JsonNode item) => items.Contains(item); + + void ICollection.CopyTo(JsonNode[] array, int arrayIndex) + { + items.CopyTo(array, arrayIndex); + } + + public bool Remove(JsonNode item) + { + return items.Remove(item); + } + + #endregion + + #region IEnumerable Members + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + IEnumerator IEnumerable.GetEnumerator() + => items.GetEnumerator(); + + #endregion + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XSet.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/Collections/XSet.cs new file mode 100644 index 00000000000..1be19ca263f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonBoolean.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonBoolean.cs new file mode 100644 index 00000000000..e1cf69408cc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonDate.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonDate.cs new file mode 100644 index 00000000000..383a6a0a27c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonNode.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonNode.cs new file mode 100644 index 00000000000..e284633c80a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonNumber.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonNumber.cs new file mode 100644 index 00000000000..fabd29ed41a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.Runtime.Json +{ + public sealed partial class JsonNumber : JsonNode + { + private readonly string value; + private readonly bool overflows = false; + + internal JsonNumber(string value) + { + this.value = value ?? throw new ArgumentNullException(nameof(value)); + } + + internal JsonNumber(int value) + { + this.value = value.ToString(); + } + + internal JsonNumber(long value) + { + this.value = value.ToString(); + + if (value > 9007199254740991) + { + overflows = true; + } + } + + internal JsonNumber(float value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal JsonNumber(double value) + { + this.value = value.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + + internal override JsonType Type => JsonType.Number; + + internal string Value => value; + + #region Helpers + + internal bool Overflows => overflows; + + internal bool IsInteger => !value.Contains("."); + + internal bool IsFloat => value.Contains("."); + + #endregion + + #region Casting + + public static implicit operator byte(JsonNumber number) + => byte.Parse(number.Value); + + public static implicit operator short(JsonNumber number) + => short.Parse(number.Value); + + public static implicit operator int(JsonNumber number) + => int.Parse(number.Value); + + public static implicit operator long(JsonNumber number) + => long.Parse(number.value); + + public static implicit operator UInt16(JsonNumber number) + => ushort.Parse(number.Value); + + public static implicit operator UInt32(JsonNumber number) + => uint.Parse(number.Value); + + public static implicit operator UInt64(JsonNumber number) + => ulong.Parse(number.Value); + + public static implicit operator decimal(JsonNumber number) + => decimal.Parse(number.Value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator Double(JsonNumber number) + => double.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator float(JsonNumber number) + => float.Parse(number.value, System.Globalization.CultureInfo.InvariantCulture); + + public static implicit operator JsonNumber(short data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(int data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(long data) + => new JsonNumber(data); + + public static implicit operator JsonNumber(Single data) + => new JsonNumber(data.ToString()); + + public static implicit operator JsonNumber(double data) + => new JsonNumber(data.ToString()); + + #endregion + + public override string ToString() => value; + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonObject.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonObject.cs new file mode 100644 index 00000000000..09a1d117882 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonString.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/JsonString.cs new file mode 100644 index 00000000000..895aaeb066f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/XBinary.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/XBinary.cs new file mode 100644 index 00000000000..8298768ae22 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/XNull.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Nodes/XNull.cs new file mode 100644 index 00000000000..33636242200 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Exceptions/ParseException.cs new file mode 100644 index 00000000000..38a20079597 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonParser.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonParser.cs new file mode 100644 index 00000000000..0c48aabce37 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonToken.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonToken.cs new file mode 100644 index 00000000000..4c34e5115a3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonTokenizer.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/JsonTokenizer.cs new file mode 100644 index 00000000000..32d9cca65d6 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Location.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Location.cs new file mode 100644 index 00000000000..b883621602c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Readers/SourceReader.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/Readers/SourceReader.cs new file mode 100644 index 00000000000..b2b2a722529 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/TokenReader.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Parser/TokenReader.cs new file mode 100644 index 00000000000..2d37f21bc70 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/PipelineMocking.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/PipelineMocking.cs new file mode 100644 index 00000000000..53396806d45 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/PipelineMocking.cs @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using System.Threading.Tasks; + using System.Collections.Generic; + using System.Net.Http; + using System.Linq; + using System.Net; + using Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.SendAsyncStep(PipelineMock instance) => instance.SendAsync; + + public MockMode Mode { get; set; } = MockMode.Live; + public PipelineMock(string recordingPath) + { + this.recordingPath = recordingPath; + } + + public void PushContext(string text) => context.Push(text); + + public void PushDescription(string text) => description.Push(text); + + + public void PushScenario(string it) + { + // reset counter too + counter = 0; + + scenario.Push(it); + } + + public void PopContext() => context.Pop(); + + public void PopDescription() => description.Pop(); + + public void PopScenario() => scenario.Pop(); + + public void SetRecord() => Mode = MockMode.Record; + + public void SetPlayback() => Mode = MockMode.Playback; + + public void SetLive() => Mode = MockMode.Live; + + public string Scenario => (scenario.Count > 0 ? scenario.Peek() : "[NoScenario]"); + public string Description => (description.Count > 0 ? description.Peek() : "[NoDescription]"); + public string Context => (context.Count > 0 ? context.Peek() : "[NoContext]"); + + /// + /// Headers that we substitute out blank values for in the recordings + /// Add additional headers as necessary + /// + public static HashSet Blacklist = new HashSet(System.StringComparer.CurrentCultureIgnoreCase) { + "Authorization", + }; + + public Dictionary ForceResponseHeaders = new Dictionary(); + + internal static XImmutableArray Removed = new XImmutableArray(new string[] { "[Filtered]" }); + + internal static IEnumerable> FilterHeaders(IEnumerable>> headers) => headers.Select(header => new KeyValuePair(header.Key, Blacklist.Contains(header.Key) ? Removed : new XImmutableArray(header.Value.ToArray()))); + + internal static JsonNode SerializeContent(HttpContent content, ref bool isBase64) => content == null ? XNull.Instance : SerializeContent(content.ReadAsByteArrayAsync().Result, ref isBase64); + + internal static JsonNode SerializeContent(byte[] content, ref bool isBase64) + { + if (null == content || content.Length == 0) + { + return XNull.Instance; + } + var first = content[0]; + var last = content[content.Length - 1]; + + // plaintext for JSON/SGML/XML/HTML/STRINGS/ARRAYS + if ((first == '{' && last == '}') || (first == '<' && last == '>') || (first == '[' && last == ']') || (first == '"' && last == '"')) + { + return new JsonString(System.Text.Encoding.UTF8.GetString(content)); + } + + // base64 for everyone else + return new JsonString(System.Convert.ToBase64String(content)); + } + + internal static byte[] DeserializeContent(string content, bool isBase64) + { + if (string.IsNullOrWhiteSpace(content)) + { + return new byte[0]; + } + + if (isBase64) + { + try + { + return System.Convert.FromBase64String(content); + } + catch + { + // hmm. didn't work, return it as a string I guess. + } + } + return System.Text.Encoding.UTF8.GetBytes(content); + } + + public void SaveMessage(string rqKey, HttpRequestMessage request, HttpResponseMessage response) + { + var messages = System.IO.File.Exists(this.recordingPath) ? Load() : new JsonObject() ?? new JsonObject(); + bool isBase64Request = false; + bool isBase64Response = false; + messages[rqKey] = new JsonObject { + { "Request",new JsonObject { + { "Method", request.Method.Method }, + { "RequestUri", request.RequestUri }, + { "Content", SerializeContent( request.Content, ref isBase64Request) }, + { "isContentBase64", isBase64Request }, + { "Headers", new JsonObject(FilterHeaders(request.Headers)) }, + { "ContentHeaders", request.Content == null ? new JsonObject() : new JsonObject(FilterHeaders(request.Content.Headers))} + } }, + {"Response", new JsonObject { + { "StatusCode", (int)response.StatusCode}, + { "Headers", new JsonObject(FilterHeaders(response.Headers))}, + { "ContentHeaders", new JsonObject(FilterHeaders(response.Content.Headers))}, + { "Content", SerializeContent(response.Content, ref isBase64Response) }, + { "isContentBase64", isBase64Response }, + }} + }; + System.IO.File.WriteAllText(this.recordingPath, messages.ToString()); + } + + private JsonObject Load() + { + if (System.IO.File.Exists(this.recordingPath)) + { + try + { + return JsonObject.FromStream(System.IO.File.OpenRead(this.recordingPath)); + } + catch + { + throw new System.Exception($"Invalid recording file: '{recordingPath}'"); + } + } + + throw new System.ArgumentException($"Missing recording file: '{recordingPath}'", nameof(recordingPath)); + } + + public HttpResponseMessage LoadMessage(string rqKey) + { + var responses = Load(); + var message = responses.Property(rqKey); + + if (null == message) + { + throw new System.ArgumentException($"Missing Request '{rqKey}' in recording file", nameof(rqKey)); + } + + var sc = 0; + var reqMessage = message.Property("Request"); + var respMessage = message.Property("Response"); + + // --------------------------- deserialize response ---------------------------------------------------------------- + bool isBase64Response = false; + respMessage.BooleanProperty("isContentBase64", ref isBase64Response); + var response = new HttpResponseMessage + { + StatusCode = (HttpStatusCode)respMessage.NumberProperty("StatusCode", ref sc), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(respMessage.StringProperty("Content"), isBase64Response)) + }; + + foreach (var each in respMessage.Property("Headers")) + { + response.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + foreach (var frh in ForceResponseHeaders) + { + response.Headers.Remove(frh.Key); + response.Headers.TryAddWithoutValidation(frh.Key, frh.Value); + } + + foreach (var each in respMessage.Property("ContentHeaders")) + { + response.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + // --------------------------- deserialize request ---------------------------------------------------------------- + bool isBase64Request = false; + reqMessage.BooleanProperty("isContentBase64", ref isBase64Request); + response.RequestMessage = new HttpRequestMessage + { + Method = new HttpMethod(reqMessage.StringProperty("Method")), + RequestUri = new System.Uri(reqMessage.StringProperty("RequestUri")), + Content = new System.Net.Http.ByteArrayContent(DeserializeContent(reqMessage.StringProperty("Content"), isBase64Request)) + }; + + foreach (var each in reqMessage.Property("Headers")) + { + response.RequestMessage.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + foreach (var each in reqMessage.Property("ContentHeaders")) + { + response.RequestMessage.Content.Headers.TryAddWithoutValidation(each.Key, each.Value.ToArrayOf()); + } + + return response; + } + + public async Task SendAsync(HttpRequestMessage request, IEventListener callback, ISendAsync next) + { + counter++; + var rqkey = $"{Description}+{Context}+{Scenario}+${request.Method.Method}+{request.RequestUri}+{counter}"; + + switch (Mode) + { + case MockMode.Record: + //Add following code since the request.Content will be released after sendAsync + var requestClone = request; + if (requestClone.Content != null) + { + requestClone = await request.CloneWithContent(request.RequestUri, request.Method); + } + // make the call + var response = await next.SendAsync(request, callback); + + // save the message to the recording file + SaveMessage(rqkey, requestClone, response); + + // return the response. + return response; + + case MockMode.Playback: + // load and return the response. + return LoadMessage(rqkey); + + default: + // pass-thru, do nothing + return await next.SendAsync(request, callback); + } + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.Designer.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.Designer.cs new file mode 100644 index 00000000000..5c81021889e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.Designer.cs @@ -0,0 +1,5655 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.generated.runtime.Properties +{ + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager + { + get + { + if (object.ReferenceEquals(resourceMan, null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Azure.PowerShell.Cmdlets.Qumulo.generated.runtime.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The remote server returned an error: (401) Unauthorized.. + /// + public static string AccessDeniedExceptionMessage + { + get + { + return ResourceManager.GetString("AccessDeniedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account id doesn't match one in subscription.. + /// + public static string AccountIdDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("AccountIdDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account needs to be specified. + /// + public static string AccountNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("AccountNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account "{0}" has been added.. + /// + public static string AddAccountAdded + { + get + { + return ResourceManager.GetString("AddAccountAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To switch to a different subscription, please use Select-AzureSubscription.. + /// + public static string AddAccountChangeSubscription + { + get + { + return ResourceManager.GetString("AddAccountChangeSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential".. + /// + public static string AddAccountNonInteractiveGuestOrFpo + { + get + { + return ResourceManager.GetString("AddAccountNonInteractiveGuestOrFpo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription "{0}" is selected as the default subscription.. + /// + public static string AddAccountShowDefaultSubscription + { + get + { + return ResourceManager.GetString("AddAccountShowDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To view all the subscriptions, please use Get-AzureSubscription.. + /// + public static string AddAccountViewSubscriptions + { + get + { + return ResourceManager.GetString("AddAccountViewSubscriptions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is created successfully.. + /// + public static string AddOnCreatedMessage + { + get + { + return ResourceManager.GetString("AddOnCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on name {0} is already used.. + /// + public static string AddOnNameAlreadyUsed + { + get + { + return ResourceManager.GetString("AddOnNameAlreadyUsed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} not found.. + /// + public static string AddOnNotFound + { + get + { + return ResourceManager.GetString("AddOnNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-on {0} is removed successfully.. + /// + public static string AddOnRemovedMessage + { + get + { + return ResourceManager.GetString("AddOnRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-On {0} is updated successfully.. + /// + public static string AddOnUpdatedMessage + { + get + { + return ResourceManager.GetString("AddOnUpdatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}.. + /// + public static string AddRoleMessageCreate + { + get + { + return ResourceManager.GetString("AddRoleMessageCreate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’.. + /// + public static string AddRoleMessageCreateNode + { + get + { + return ResourceManager.GetString("AddRoleMessageCreateNode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure".. + /// + public static string AddRoleMessageCreatePHP + { + get + { + return ResourceManager.GetString("AddRoleMessageCreatePHP", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator. + /// + public static string AddRoleMessageInsufficientPermissions + { + get + { + return ResourceManager.GetString("AddRoleMessageInsufficientPermissions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A role name '{0}' already exists. + /// + public static string AddRoleMessageRoleExists + { + get + { + return ResourceManager.GetString("AddRoleMessageRoleExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} already has an endpoint with name {1}. + /// + public static string AddTrafficManagerEndpointFailed + { + get + { + return ResourceManager.GetString("AddTrafficManagerEndpointFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. + ///Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable [rest of string was truncated]";. + /// + public static string ARMDataCollectionMessage + { + get + { + return ResourceManager.GetString("ARMDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [Common.Authentication]: Authenticating for account {0} with single tenant {1}.. + /// + public static string AuthenticatingForSingleTenant + { + get + { + return ResourceManager.GetString("AuthenticatingForSingleTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Windows Azure Powershell\. + /// + public static string AzureDirectory + { + get + { + return ResourceManager.GetString("AzureDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://manage.windowsazure.com. + /// + public static string AzurePortalUrl + { + get + { + return ResourceManager.GetString("AzurePortalUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PORTAL_URL. + /// + public static string AzurePortalUrlEnv + { + get + { + return ResourceManager.GetString("AzurePortalUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected profile must not be null.. + /// + public static string AzureProfileMustNotBeNull + { + get + { + return ResourceManager.GetString("AzureProfileMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure SDK\{0}\. + /// + public static string AzureSdkDirectory + { + get + { + return ResourceManager.GetString("AzureSdkDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscArchiveAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscArchiveAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find configuration data file: {0}. + /// + public static string AzureVMDscCannotFindConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscCannotFindConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Create Archive. + /// + public static string AzureVMDscCreateArchiveAction + { + get + { + return ResourceManager.GetString("AzureVMDscCreateArchiveAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The configuration data must be a .psd1 file. + /// + public static string AzureVMDscInvalidConfigurationDataFile + { + get + { + return ResourceManager.GetString("AzureVMDscInvalidConfigurationDataFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parsing configuration script: {0}. + /// + public static string AzureVMDscParsingConfiguration + { + get + { + return ResourceManager.GetString("AzureVMDscParsingConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it.. + /// + public static string AzureVMDscStorageBlobAlreadyExists + { + get + { + return ResourceManager.GetString("AzureVMDscStorageBlobAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upload '{0}'. + /// + public static string AzureVMDscUploadToBlobStorageAction + { + get + { + return ResourceManager.GetString("AzureVMDscUploadToBlobStorageAction", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Execution failed because a background thread could not prompt the user.. + /// + public static string BaseShouldMethodFailureReason + { + get + { + return ResourceManager.GetString("BaseShouldMethodFailureReason", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Base Uri was empty.. + /// + public static string BaseUriEmpty + { + get + { + return ResourceManager.GetString("BaseUriEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing without ParameterSet.. + /// + public static string BeginProcessingWithoutParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithoutParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} begin processing with ParameterSet '{1}'.. + /// + public static string BeginProcessingWithParameterSetLog + { + get + { + return ResourceManager.GetString("BeginProcessingWithParameterSetLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Blob with the name {0} already exists in the account.. + /// + public static string BlobAlreadyExistsInTheAccount + { + get + { + return ResourceManager.GetString("BlobAlreadyExistsInTheAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}.blob.core.windows.net/. + /// + public static string BlobEndpointUri + { + get + { + return ResourceManager.GetString("BlobEndpointUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_BLOBSTORAGE_TEMPLATE. + /// + public static string BlobEndpointUriEnv + { + get + { + return ResourceManager.GetString("BlobEndpointUriEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is changing.. + /// + public static string BreakingChangeAttributeParameterChanging + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterChanging", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is becoming mandatory.. + /// + public static string BreakingChangeAttributeParameterMandatoryNow + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterMandatoryNow", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplaced + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplaced", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The parameter : '{0}' is being replaced by mandatory parameter : '{1}'.. + /// + public static string BreakingChangeAttributeParameterReplacedMandatory + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterReplacedMandatory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The type of the parameter is changing from '{0}' to '{1}'.. + /// + public static string BreakingChangeAttributeParameterTypeChange + { + get + { + return ResourceManager.GetString("BreakingChangeAttributeParameterTypeChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Change description : {0} + ///. + /// + public static string BreakingChangesAttributesChangeDescriptionMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesChangeDescriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet is being deprecated. There will be no replacement for it.. + /// + public static string BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesParameterSetDeprecationMessageNoReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet '{0}' is replacing this cmdlet.. + /// + public static string BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetDeprecationMessageWithReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type is changing from the existing type :'{0}' to the new type :'{1}'. + /// + public static string BreakingChangesAttributesCmdLetOutputChange1 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange1", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "The output type '{0}' is changing". + /// + public static string BreakingChangesAttributesCmdLetOutputChange2 + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputChange2", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + ///- The following properties are being added to the output type : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesAdded + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesAdded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to + /// - The following properties in the output type are being deprecated : + ///. + /// + public static string BreakingChangesAttributesCmdLetOutputPropertiesRemoved + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputPropertiesRemoved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The output type '{0}' is being deprecated without a replacement.. + /// + public static string BreakingChangesAttributesCmdLetOutputTypeDeprecated + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesCmdLetOutputTypeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - {0} + /// + ///. + /// + public static string BreakingChangesAttributesDeclarationMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to - Cmdlet : '{0}' + /// - {1} + ///. + /// + public static string BreakingChangesAttributesDeclarationMessageWithCmdletName + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesDeclarationMessageWithCmdletName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to NOTE : Go to {0} for steps to suppress (and other related information on) the breaking change messages.. + /// + public static string BreakingChangesAttributesFooterMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesFooterMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Breaking changes in the cmdlet '{0}' :. + /// + public static string BreakingChangesAttributesHeaderMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesHeaderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note : This change will take effect on '{0}' + ///. + /// + public static string BreakingChangesAttributesInEffectByDateMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByDateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note :The change is expected to take effect from az version : '{0}' + /// + ///. + /// + public static string BreakingChangesAttributesInEffectByAzVersion + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesInEffectByAzVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ```powershell + ///# Old + ///{0} + /// + ///# New + ///{1} + ///``` + /// + ///. + /// + public static string BreakingChangesAttributesUsageChangeMessage + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cmdlet invocation changes : + /// Old Way : {0} + /// New Way : {1}. + /// + public static string BreakingChangesAttributesUsageChangeMessageConsole + { + get + { + return ResourceManager.GetString("BreakingChangesAttributesUsageChangeMessageConsole", resourceCulture); + } + } + + /// + /// The cmdlet is in experimental stage. The function may not be enabled in current subscription. + /// + public static string ExperimentalCmdletMessage + { + get + { + return ResourceManager.GetString("ExperimentalCmdletMessage", resourceCulture); + } + } + + + + /// + /// Looks up a localized string similar to CACHERUNTIMEURL. + /// + public static string CacheRuntimeUrl + { + get + { + return ResourceManager.GetString("CacheRuntimeUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cache. + /// + public static string CacheRuntimeValue + { + get + { + return ResourceManager.GetString("CacheRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to CacheRuntimeVersion. + /// + public static string CacheRuntimeVersionKey + { + get + { + return ResourceManager.GetString("CacheRuntimeVersionKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}). + /// + public static string CacheVersionWarningText + { + get + { + return ResourceManager.GetString("CacheVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot change built-in environment {0}.. + /// + public static string CannotChangeBuiltinEnvironment + { + get + { + return ResourceManager.GetString("CannotChangeBuiltinEnvironment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find {0} with name {1}.. + /// + public static string CannotFind + { + get + { + return ResourceManager.GetString("CannotFind", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment for service {0} with {1} slot doesn't exist. + /// + public static string CannotFindDeployment + { + get + { + return ResourceManager.GetString("CannotFindDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't find valid Microsoft Azure role in current directory {0}. + /// + public static string CannotFindRole + { + get + { + return ResourceManager.GetString("CannotFindRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist. + /// + public static string CannotFindServiceConfigurationFile + { + get + { + return ResourceManager.GetString("CannotFindServiceConfigurationFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders.. + /// + public static string CannotFindServiceRoot + { + get + { + return ResourceManager.GetString("CannotFindServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated.. + /// + public static string CannotUpdateUnknownSubscription + { + get + { + return ResourceManager.GetString("CannotUpdateUnknownSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ManagementCertificate. + /// + public static string CertificateElementName + { + get + { + return ResourceManager.GetString("CertificateElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to certificate.pfx. + /// + public static string CertificateFileName + { + get + { + return ResourceManager.GetString("CertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate imported into CurrentUser\My\{0}. + /// + public static string CertificateImportedMessage + { + get + { + return ResourceManager.GetString("CertificateImportedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No certificate was found in the certificate store with thumbprint {0}. + /// + public static string CertificateNotFoundInStore + { + get + { + return ResourceManager.GetString("CertificateNotFoundInStore", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your account does not have access to the private key for certificate {0}. + /// + public static string CertificatePrivateKeyAccessError + { + get + { + return ResourceManager.GetString("CertificatePrivateKeyAccessError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} {1} deployment for {2} service. + /// + public static string ChangeDeploymentStateWaitMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStateWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cloud service {0} is in {1} state.. + /// + public static string ChangeDeploymentStatusCompleteMessage + { + get + { + return ResourceManager.GetString("ChangeDeploymentStatusCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing/Removing public environment '{0}' is not allowed.. + /// + public static string ChangePublicEnvironmentMessage + { + get + { + return ResourceManager.GetString("ChangePublicEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} is set to value {1}. + /// + public static string ChangeSettingsElementMessage + { + get + { + return ResourceManager.GetString("ChangeSettingsElementMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Changing public environment is not supported.. + /// + public static string ChangingDefaultEnvironmentNotSupported + { + get + { + return ResourceManager.GetString("ChangingDefaultEnvironmentNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Choose which publish settings file to use:. + /// + public static string ChoosePublishSettingsFile + { + get + { + return ResourceManager.GetString("ChoosePublishSettingsFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel. + /// + public static string ClientDiagnosticLevelName + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string ClientDiagnosticLevelValue + { + get + { + return ResourceManager.GetString("ClientDiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to cloud_package.cspkg. + /// + public static string CloudPackageFileName + { + get + { + return ResourceManager.GetString("CloudPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Cloud.cscfg. + /// + public static string CloudServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("CloudServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Add-ons for {0}. + /// + public static string CloudServiceDescription + { + get + { + return ResourceManager.GetString("CloudServiceDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive.. + /// + public static string CommunicationCouldNotBeEstablished + { + get + { + return ResourceManager.GetString("CommunicationCouldNotBeEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete. + /// + public static string CompleteMessage + { + get + { + return ResourceManager.GetString("CompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to OperationID : '{0}'. + /// + public static string ComputeCloudExceptionOperationIdMessage + { + get + { + return ResourceManager.GetString("ComputeCloudExceptionOperationIdMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to config.json. + /// + public static string ConfigurationFileName + { + get + { + return ResourceManager.GetString("ConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to VirtualMachine creation failed.. + /// + public static string CreateFailedErrorMessage + { + get + { + return ResourceManager.GetString("CreateFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead.. + /// + public static string CreateWebsiteFailed + { + get + { + return ResourceManager.GetString("CreateWebsiteFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core. + /// + public static string DataCacheClientsType + { + get + { + return ResourceManager.GetString("DataCacheClientsType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //blobcontainer[@datacenter='{0}']. + /// + public static string DatacenterBlobQuery + { + get + { + return ResourceManager.GetString("DatacenterBlobQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure PowerShell Data Collection Confirmation. + /// + public static string DataCollectionActivity + { + get + { + return ResourceManager.GetString("DataCollectionActivity", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose not to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmNo + { + get + { + return ResourceManager.GetString("DataCollectionConfirmNo", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This confirmation message will be dismissed in '{0}' second(s).... + /// + public static string DataCollectionConfirmTime + { + get + { + return ResourceManager.GetString("DataCollectionConfirmTime", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You choose to participate in Microsoft Azure PowerShell data collection.. + /// + public static string DataCollectionConfirmYes + { + get + { + return ResourceManager.GetString("DataCollectionConfirmYes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The setting profile has been saved to the following path '{0}'.. + /// + public static string DataCollectionSaveFileInformation + { + get + { + return ResourceManager.GetString("DataCollectionSaveFileInformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription. + /// + public static string DefaultAndCurrentSubscription + { + get + { + return ResourceManager.GetString("DefaultAndCurrentSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none. + /// + public static string DefaultFileVersion + { + get + { + return ResourceManager.GetString("DefaultFileVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There are no hostnames which could be used for validation.. + /// + public static string DefaultHostnamesValidation + { + get + { + return ResourceManager.GetString("DefaultHostnamesValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 8080. + /// + public static string DefaultPort + { + get + { + return ResourceManager.GetString("DefaultPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string DefaultRoleCachingInMB + { + get + { + return ResourceManager.GetString("DefaultRoleCachingInMB", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Auto. + /// + public static string DefaultUpgradeMode + { + get + { + return ResourceManager.GetString("DefaultUpgradeMode", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 80. + /// + public static string DefaultWebPort + { + get + { + return ResourceManager.GetString("DefaultWebPort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete. + /// + public static string Delete + { + get + { + return ResourceManager.GetString("Delete", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for service {1} is already in {2} state. + /// + public static string DeploymentAlreadyInState + { + get + { + return ResourceManager.GetString("DeploymentAlreadyInState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment in {0} slot for service {1} is removed. + /// + public static string DeploymentRemovedMessage + { + get + { + return ResourceManager.GetString("DeploymentRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel. + /// + public static string DiagnosticLevelName + { + get + { + return ResourceManager.GetString("DiagnosticLevelName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1. + /// + public static string DiagnosticLevelValue + { + get + { + return ResourceManager.GetString("DiagnosticLevelValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The key to add already exists in the dictionary.. + /// + public static string DictionaryAddAlreadyContainsKey + { + get + { + return ResourceManager.GetString("DictionaryAddAlreadyContainsKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The array index cannot be less than zero.. + /// + public static string DictionaryCopyToArrayIndexLessThanZero + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayIndexLessThanZero", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The supplied array does not have enough room to contain the copied elements.. + /// + public static string DictionaryCopyToArrayTooShort + { + get + { + return ResourceManager.GetString("DictionaryCopyToArrayTooShort", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided dns {0} doesn't exist. + /// + public static string DnsDoesNotExist + { + get + { + return ResourceManager.GetString("DnsDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft Azure Certificate. + /// + public static string EnableRemoteDesktop_FriendlyCertificateName + { + get + { + return ResourceManager.GetString("EnableRemoteDesktop_FriendlyCertificateName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Endpoint can't be retrieved for storage account. + /// + public static string EndPointNotFoundForBlobStorage + { + get + { + return ResourceManager.GetString("EndPointNotFoundForBlobStorage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} end processing.. + /// + public static string EndProcessingLog + { + get + { + return ResourceManager.GetString("EndProcessingLog", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet.. + /// + public static string EnvironmentDoesNotSupportActiveDirectory + { + get + { + return ResourceManager.GetString("EnvironmentDoesNotSupportActiveDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment '{0}' already exists.. + /// + public static string EnvironmentExists + { + get + { + return ResourceManager.GetString("EnvironmentExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name doesn't match one in subscription.. + /// + public static string EnvironmentNameDoesntMatchSubscription + { + get + { + return ResourceManager.GetString("EnvironmentNameDoesntMatchSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment name needs to be specified.. + /// + public static string EnvironmentNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Environment needs to be specified.. + /// + public static string EnvironmentNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("EnvironmentNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The environment name '{0}' is not found.. + /// + public static string EnvironmentNotFound + { + get + { + return ResourceManager.GetString("EnvironmentNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to environments.xml. + /// + public static string EnvironmentsFileName + { + get + { + return ResourceManager.GetString("EnvironmentsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error creating VirtualMachine. + /// + public static string ErrorCreatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorCreatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to download available runtimes for location '{0}'. + /// + public static string ErrorRetrievingRuntimesForLocation + { + get + { + return ResourceManager.GetString("ErrorRetrievingRuntimesForLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating VirtualMachine. + /// + public static string ErrorUpdatingVirtualMachine + { + get + { + return ResourceManager.GetString("ErrorUpdatingVirtualMachine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} failed. Error: {1}, ExceptionDetails: {2}. + /// + public static string FailedJobErrorMessage + { + get + { + return ResourceManager.GetString("FailedJobErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File path is not valid.. + /// + public static string FilePathIsNotValid + { + get + { + return ResourceManager.GetString("FilePathIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The HTTP request was forbidden with client authentication scheme 'Anonymous'.. + /// + public static string FirstPurchaseErrorMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell.. + /// + public static string FirstPurchaseMessage + { + get + { + return ResourceManager.GetString("FirstPurchaseMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation Status:. + /// + public static string GatewayOperationStatus + { + get + { + return ResourceManager.GetString("GatewayOperationStatus", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\General. + /// + public static string GeneralScaffolding + { + get + { + return ResourceManager.GetString("GeneralScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Getting all available Microsoft Azure Add-Ons, this may take few minutes.... + /// + public static string GetAllAddOnsWaitMessage + { + get + { + return ResourceManager.GetString("GetAllAddOnsWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name{0}Primary Key{0}Seconday Key. + /// + public static string GetStorageKeysHeader + { + get + { + return ResourceManager.GetString("GetStorageKeysHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Git not found. Please install git and place it in your command line path.. + /// + public static string GitNotFound + { + get + { + return ResourceManager.GetString("GitNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not find publish settings. Please run Import-AzurePublishSettingsFile.. + /// + public static string GlobalSettingsManager_Load_PublishSettingsNotFound + { + get + { + return ResourceManager.GetString("GlobalSettingsManager_Load_PublishSettingsNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg end element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoEndWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoEndWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WadCfg start element in the config is not matching the end element.. + /// + public static string IaasDiagnosticsBadConfigNoMatchingWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoMatchingWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find the WadCfg element in the config.. + /// + public static string IaasDiagnosticsBadConfigNoWadCfg + { + get + { + return ResourceManager.GetString("IaasDiagnosticsBadConfigNoWadCfg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode.dll. + /// + public static string IISNodeDll + { + get + { + return ResourceManager.GetString("IISNodeDll", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeEngineKey + { + get + { + return ResourceManager.GetString("IISNodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode-dev\\release\\x64. + /// + public static string IISNodePath + { + get + { + return ResourceManager.GetString("IISNodePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to iisnode. + /// + public static string IISNodeRuntimeValue + { + get + { + return ResourceManager.GetString("IISNodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}). + /// + public static string IISNodeVersionWarningText + { + get + { + return ResourceManager.GetString("IISNodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Illegal characters in path.. + /// + public static string IllegalPath + { + get + { + return ResourceManager.GetString("IllegalPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. + /// + public static string InternalServerErrorMessage + { + get + { + return ResourceManager.GetString("InternalServerErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot enable memcach protocol on a cache worker role {0}.. + /// + public static string InvalidCacheRoleName + { + get + { + return ResourceManager.GetString("InvalidCacheRoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings. + /// + public static string InvalidCertificate + { + get + { + return ResourceManager.GetString("InvalidCertificate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid certificate format.. + /// + public static string InvalidCertificateSingle + { + get + { + return ResourceManager.GetString("InvalidCertificateSingle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided configuration path is invalid or doesn't exist. + /// + public static string InvalidConfigPath + { + get + { + return ResourceManager.GetString("InvalidConfigPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2.. + /// + public static string InvalidCountryNameMessage + { + get + { + return ResourceManager.GetString("InvalidCountryNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription.. + /// + public static string InvalidDefaultSubscription + { + get + { + return ResourceManager.GetString("InvalidDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deployment with {0} does not exist. + /// + public static string InvalidDeployment + { + get + { + return ResourceManager.GetString("InvalidDeployment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production".. + /// + public static string InvalidDeploymentSlot + { + get + { + return ResourceManager.GetString("InvalidDeploymentSlot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "{0}" is an invalid DNS name for {1}. + /// + public static string InvalidDnsName + { + get + { + return ResourceManager.GetString("InvalidDnsName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid service endpoint.. + /// + public static string InvalidEndpoint + { + get + { + return ResourceManager.GetString("InvalidEndpoint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided file in {0} must be have {1} extension. + /// + public static string InvalidFileExtension + { + get + { + return ResourceManager.GetString("InvalidFileExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to File {0} has invalid characters. + /// + public static string InvalidFileName + { + get + { + return ResourceManager.GetString("InvalidFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your git publishing credentials using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. On the left side open "Web Sites" + ///2. Click on any website + ///3. Choose "Setup Git Publishing" or "Reset deployment credentials" + ///4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username}. + /// + public static string InvalidGitCredentials + { + get + { + return ResourceManager.GetString("InvalidGitCredentials", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The value {0} provided is not a valid GUID. Please provide a valid GUID.. + /// + public static string InvalidGuid + { + get + { + return ResourceManager.GetString("InvalidGuid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified hostname does not exist. Please specify a valid hostname for the site.. + /// + public static string InvalidHostnameValidation + { + get + { + return ResourceManager.GetString("InvalidHostnameValidation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances must be greater than or equal 0 and less than or equal 20. + /// + public static string InvalidInstancesCount + { + get + { + return ResourceManager.GetString("InvalidInstancesCount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file.. + /// + public static string InvalidJobFile + { + get + { + return ResourceManager.GetString("InvalidJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not download a valid runtime manifest, Please check your internet connection and try again.. + /// + public static string InvalidManifestError + { + get + { + return ResourceManager.GetString("InvalidManifestError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The account {0} was not found. Please specify a valid account name.. + /// + public static string InvalidMediaServicesAccount + { + get + { + return ResourceManager.GetString("InvalidMediaServicesAccount", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided name "{0}" does not match the service bus namespace naming rules.. + /// + public static string InvalidNamespaceName + { + get + { + return ResourceManager.GetString("InvalidNamespaceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path must specify a valid path to an Azure profile.. + /// + public static string InvalidNewProfilePath + { + get + { + return ResourceManager.GetString("InvalidNewProfilePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be null. Parameter name: '{0}'. + /// + public static string InvalidNullArgument + { + get + { + return ResourceManager.GetString("InvalidNullArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is invalid or empty. + /// + public static string InvalidOrEmptyArgumentMessage + { + get + { + return ResourceManager.GetString("InvalidOrEmptyArgumentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided package path is invalid or doesn't exist. + /// + public static string InvalidPackagePath + { + get + { + return ResourceManager.GetString("InvalidPackagePath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' is an invalid parameter set name.. + /// + public static string InvalidParameterSetName + { + get + { + return ResourceManager.GetString("InvalidParameterSetName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} doesn't exist in {1} or you've not passed valid value for it. + /// + public static string InvalidPath + { + get + { + return ResourceManager.GetString("InvalidPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} has invalid characters. + /// + public static string InvalidPathName + { + get + { + return ResourceManager.GetString("InvalidPathName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token}. + /// + public static string InvalidProfileProperties + { + get + { + return ResourceManager.GetString("InvalidProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile. + /// + public static string InvalidPublishSettingsSchema + { + get + { + return ResourceManager.GetString("InvalidPublishSettingsSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name "{0}" has invalid characters. + /// + public static string InvalidRoleNameMessage + { + get + { + return ResourceManager.GetString("InvalidRoleNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid name for the service root folder is required. + /// + public static string InvalidRootNameMessage + { + get + { + return ResourceManager.GetString("InvalidRootNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} is not a recognized runtime type. + /// + public static string InvalidRuntimeError + { + get + { + return ResourceManager.GetString("InvalidRuntimeError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid language is required. + /// + public static string InvalidScaffoldingLanguageArg + { + get + { + return ResourceManager.GetString("InvalidScaffoldingLanguageArg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscription is currently selected. Use Select-Subscription to activate a subscription.. + /// + public static string InvalidSelectedSubscription + { + get + { + return ResourceManager.GetString("InvalidSelectedSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations.. + /// + public static string InvalidServiceBusLocation + { + get + { + return ResourceManager.GetString("InvalidServiceBusLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide a service name or run this command from inside a service project directory.. + /// + public static string InvalidServiceName + { + get + { + return ResourceManager.GetString("InvalidServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must provide valid value for {0}. + /// + public static string InvalidServiceSettingElement + { + get + { + return ResourceManager.GetString("InvalidServiceSettingElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to settings.json is invalid or doesn't exist. + /// + public static string InvalidServiceSettingMessage + { + get + { + return ResourceManager.GetString("InvalidServiceSettingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data.. + /// + public static string InvalidSubscription + { + get + { + return ResourceManager.GetString("InvalidSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscription id {0} is not valid. + /// + public static string InvalidSubscriptionId + { + get + { + return ResourceManager.GetString("InvalidSubscriptionId", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Must specify a non-null subscription name.. + /// + public static string InvalidSubscriptionName + { + get + { + return ResourceManager.GetString("InvalidSubscriptionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet. + /// + public static string InvalidSubscriptionNameMessage + { + get + { + return ResourceManager.GetString("InvalidSubscriptionNameMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided subscriptions file {0} has invalid content.. + /// + public static string InvalidSubscriptionsDataSchema + { + get + { + return ResourceManager.GetString("InvalidSubscriptionsDataSchema", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge.. + /// + public static string InvalidVMSize + { + get + { + return ResourceManager.GetString("InvalidVMSize", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The web job file must have *.zip extension. + /// + public static string InvalidWebJobFile + { + get + { + return ResourceManager.GetString("InvalidWebJobFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Singleton option works for continuous jobs only.. + /// + public static string InvalidWebJobSingleton + { + get + { + return ResourceManager.GetString("InvalidWebJobSingleton", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The website {0} was not found. Please specify a valid website name.. + /// + public static string InvalidWebsite + { + get + { + return ResourceManager.GetString("InvalidWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No job for id: {0} was found.. + /// + public static string JobNotFound + { + get + { + return ResourceManager.GetString("JobNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to engines. + /// + public static string JsonEnginesSectionName + { + get + { + return ResourceManager.GetString("JsonEnginesSectionName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Scaffolding for this language is not yet supported. + /// + public static string LanguageScaffoldingIsNotSupported + { + get + { + return ResourceManager.GetString("LanguageScaffoldingIsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Link already established. + /// + public static string LinkAlreadyEstablished + { + get + { + return ResourceManager.GetString("LinkAlreadyEstablished", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to local_package.csx. + /// + public static string LocalPackageFileName + { + get + { + return ResourceManager.GetString("LocalPackageFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceConfiguration.Local.cscfg. + /// + public static string LocalServiceConfigurationFileName + { + get + { + return ResourceManager.GetString("LocalServiceConfigurationFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for {0} deployment for {1} cloud service.... + /// + public static string LookingForDeploymentMessage + { + get + { + return ResourceManager.GetString("LookingForDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Looking for cloud service {0}.... + /// + public static string LookingForServiceMessage + { + get + { + return ResourceManager.GetString("LookingForServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure Long-Running Job. + /// + public static string LROJobName + { + get + { + return ResourceManager.GetString("LROJobName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter.. + /// + public static string LROTaskExceptionMessage + { + get + { + return ResourceManager.GetString("LROTaskExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to managementCertificate.pem. + /// + public static string ManagementCertificateFileName + { + get + { + return ResourceManager.GetString("ManagementCertificateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ?whr={0}. + /// + public static string ManagementPortalRealmFormat + { + get + { + return ResourceManager.GetString("ManagementPortalRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to //baseuri. + /// + public static string ManifestBaseUriQuery + { + get + { + return ResourceManager.GetString("ManifestBaseUriQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to uri. + /// + public static string ManifestBlobUriKey + { + get + { + return ResourceManager.GetString("ManifestBlobUriKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml. + /// + public static string ManifestUri + { + get + { + return ResourceManager.GetString("ManifestUri", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'.. + /// + public static string MissingCertificateInProfileProperties + { + get + { + return ResourceManager.GetString("MissingCertificateInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'.. + /// + public static string MissingPasswordInProfileProperties + { + get + { + return ResourceManager.GetString("MissingPasswordInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property bag Hashtable must contain a 'SubscriptionId'.. + /// + public static string MissingSubscriptionInProfileProperties + { + get + { + return ResourceManager.GetString("MissingSubscriptionInProfileProperties", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple Add-Ons found holding name {0}. + /// + public static string MultipleAddOnsFoundMessage + { + get + { + return ResourceManager.GetString("MultipleAddOnsFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername.. + /// + public static string MultiplePublishingUsernames + { + get + { + return ResourceManager.GetString("MultiplePublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The first publish settings file "{0}" is used. If you want to use another file specify the file name.. + /// + public static string MultiplePublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("MultiplePublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Plugins.Caching.NamedCaches. + /// + public static string NamedCacheSettingName + { + get + { + return ResourceManager.GetString("NamedCacheSettingName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]}. + /// + public static string NamedCacheSettingValue + { + get + { + return ResourceManager.GetString("NamedCacheSettingValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A publishing username is required. Please specify one using the argument PublishingUsername.. + /// + public static string NeedPublishingUsernames + { + get + { + return ResourceManager.GetString("NeedPublishingUsernames", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to New Add-On Confirmation. + /// + public static string NewAddOnConformation + { + get + { + return ResourceManager.GetString("NewAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string NewMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names.. + /// + public static string NewNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("NewNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at {0} and (c) agree to sharing my contact information with {2}.. + /// + public static string NewNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("NewNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service has been created at {0}. + /// + public static string NewServiceCreatedMessage + { + get + { + return ResourceManager.GetString("NewServiceCreatedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No. + /// + public static string No + { + get + { + return ResourceManager.GetString("No", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription.. + /// + public static string NoCachedToken + { + get + { + return ResourceManager.GetString("NoCachedToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole.. + /// + public static string NoCacheWorkerRoles + { + get + { + return ResourceManager.GetString("NoCacheWorkerRoles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No clouds available. + /// + public static string NoCloudsAvailable + { + get + { + return ResourceManager.GetString("NoCloudsAvailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "There is no current context, please log in using Connect-AzAccount.". + /// + public static string NoCurrentContextForDataCmdlet + { + get + { + return ResourceManager.GetString("NoCurrentContextForDataCmdlet", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeDirectory + { + get + { + return ResourceManager.GetString("NodeDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeEngineKey + { + get + { + return ResourceManager.GetString("NodeEngineKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node.exe. + /// + public static string NodeExe + { + get + { + return ResourceManager.GetString("NodeExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name>. + /// + public static string NoDefaultSubscriptionMessage + { + get + { + return ResourceManager.GetString("NoDefaultSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft SDKs\Azure\Nodejs\Nov2011. + /// + public static string NodeModulesPath + { + get + { + return ResourceManager.GetString("NodeModulesPath", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to nodejs. + /// + public static string NodeProgramFilesFolderName + { + get + { + return ResourceManager.GetString("NodeProgramFilesFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to node. + /// + public static string NodeRuntimeValue + { + get + { + return ResourceManager.GetString("NodeRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\Node. + /// + public static string NodeScaffolding + { + get + { + return ResourceManager.GetString("NodeScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node. + /// + public static string NodeScaffoldingResources + { + get + { + return ResourceManager.GetString("NodeScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}). + /// + public static string NodeVersionWarningText + { + get + { + return ResourceManager.GetString("NodeVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No, I do not agree. + /// + public static string NoHint + { + get + { + return ResourceManager.GetString("NoHint", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please connect to internet before executing this cmdlet. + /// + public static string NoInternetConnection + { + get + { + return ResourceManager.GetString("NoInternetConnection", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to <NONE>. + /// + public static string None + { + get + { + return ResourceManager.GetString("None", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No publish settings files with extension *.publishsettings are found in the directory "{0}".. + /// + public static string NoPublishSettingsFilesFoundMessage + { + get + { + return ResourceManager.GetString("NoPublishSettingsFilesFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to There is no subscription associated with account {0}.. + /// + public static string NoSubscriptionAddedMessage + { + get + { + return ResourceManager.GetString("NoSubscriptionAddedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount?. + /// + public static string NoSubscriptionFoundForTenant + { + get + { + return ResourceManager.GetString("NoSubscriptionFoundForTenant", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration.. + /// + public static string NotCacheWorkerRole + { + get + { + return ResourceManager.GetString("NotCacheWorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Certificate can't be null.. + /// + public static string NullCertificateMessage + { + get + { + return ResourceManager.GetString("NullCertificateMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} could not be null or empty. + /// + public static string NullObjectMessage + { + get + { + return ResourceManager.GetString("NullObjectMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add a null RoleSettings to {0}. + /// + public static string NullRoleSettingsMessage + { + get + { + return ResourceManager.GetString("NullRoleSettingsMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to add new role to null service definition. + /// + public static string NullServiceDefinitionMessage + { + get + { + return ResourceManager.GetString("NullServiceDefinitionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The request offer '{0}' is not found.. + /// + public static string OfferNotFoundMessage + { + get + { + return ResourceManager.GetString("OfferNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Operation "{0}" failed on VM with ID: {1}. + /// + public static string OperationFailedErrorMessage + { + get + { + return ResourceManager.GetString("OperationFailedErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The REST operation failed with message '{0}' and error code '{1}'. + /// + public static string OperationFailedMessage + { + get + { + return ResourceManager.GetString("OperationFailedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state.. + /// + public static string OperationTimedOutOrError + { + get + { + return ResourceManager.GetString("OperationTimedOutOrError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package. + /// + public static string Package + { + get + { + return ResourceManager.GetString("Package", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package is created at service root path {0}.. + /// + public static string PackageCreated + { + get + { + return ResourceManager.GetString("PackageCreated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {{ + /// "author": "", + /// + /// "name": "{0}", + /// "version": "0.0.0", + /// "dependencies":{{}}, + /// "devDependencies":{{}}, + /// "optionalDependencies": {{}}, + /// "engines": {{ + /// "node": "*", + /// "iisnode": "*" + /// }} + /// + ///}} + ///. + /// + public static string PackageJsonDefaultFile + { + get + { + return ResourceManager.GetString("PackageJsonDefaultFile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to package.json. + /// + public static string PackageJsonFileName + { + get + { + return ResourceManager.GetString("PackageJsonFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path {0} doesn't exist.. + /// + public static string PathDoesNotExist + { + get + { + return ResourceManager.GetString("PathDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path for {0} doesn't exist in {1}.. + /// + public static string PathDoesNotExistForElement + { + get + { + return ResourceManager.GetString("PathDoesNotExistForElement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Peer Asn has to be provided.. + /// + public static string PeerAsnRequired + { + get + { + return ResourceManager.GetString("PeerAsnRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 5.4.0. + /// + public static string PHPDefaultRuntimeVersion + { + get + { + return ResourceManager.GetString("PHPDefaultRuntimeVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to php. + /// + public static string PhpRuntimeValue + { + get + { + return ResourceManager.GetString("PhpRuntimeValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resources\Scaffolding\PHP. + /// + public static string PHPScaffolding + { + get + { + return ResourceManager.GetString("PHPScaffolding", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP. + /// + public static string PHPScaffoldingResources + { + get + { + return ResourceManager.GetString("PHPScaffoldingResources", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}). + /// + public static string PHPVersionWarningText + { + get + { + return ResourceManager.GetString("PHPVersionWarningText", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must create your first web site using the Microsoft Azure portal. + ///Please follow these steps in the portal: + ///1. At the bottom of the page, click on New > Web Site > Quick Create + ///2. Type {0} in the URL field + ///3. Click on "Create Web Site" + ///4. Once the site has been created, click on the site name + ///5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create.. + /// + public static string PortalInstructions + { + get + { + return ResourceManager.GetString("PortalInstructions", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git". + /// + public static string PortalInstructionsGit + { + get + { + return ResourceManager.GetString("PortalInstructionsGit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The estimated generally available date is '{0}'.. + /// + public static string PreviewCmdletETAMessage { + get { + return ResourceManager.GetString("PreviewCmdletETAMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to This cmdlet is in preview. Its behavior is subject to change based on customer feedback.. + /// + public static string PreviewCmdletMessage + { + get + { + return ResourceManager.GetString("PreviewCmdletMessage", resourceCulture); + } + } + + + /// + /// Looks up a localized string similar to A value for the Primary Peer Subnet has to be provided.. + /// + public static string PrimaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("PrimaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Promotion code can be used only when updating to a new plan.. + /// + public static string PromotionCodeWithCurrentPlanMessage + { + get + { + return ResourceManager.GetString("PromotionCodeWithCurrentPlanMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service not published at user request.. + /// + public static string PublishAbortedAtUserRequest + { + get + { + return ResourceManager.GetString("PublishAbortedAtUserRequest", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Complete.. + /// + public static string PublishCompleteMessage + { + get + { + return ResourceManager.GetString("PublishCompleteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Connecting.... + /// + public static string PublishConnectingMessage + { + get + { + return ResourceManager.GetString("PublishConnectingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Deployment ID: {0}.. + /// + public static string PublishCreatedDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishCreatedDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created hosted service '{0}'.. + /// + public static string PublishCreatedServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatedServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Created Website URL: {0}.. + /// + public static string PublishCreatedWebsiteMessage + { + get + { + return ResourceManager.GetString("PublishCreatedWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creating.... + /// + public static string PublishCreatingServiceMessage + { + get + { + return ResourceManager.GetString("PublishCreatingServiceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Initializing.... + /// + public static string PublishInitializingMessage + { + get + { + return ResourceManager.GetString("PublishInitializingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to busy. + /// + public static string PublishInstanceStatusBusy + { + get + { + return ResourceManager.GetString("PublishInstanceStatusBusy", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to creating the virtual machine. + /// + public static string PublishInstanceStatusCreating + { + get + { + return ResourceManager.GetString("PublishInstanceStatusCreating", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Instance {0} of role {1} is {2}.. + /// + public static string PublishInstanceStatusMessage + { + get + { + return ResourceManager.GetString("PublishInstanceStatusMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ready. + /// + public static string PublishInstanceStatusReady + { + get + { + return ResourceManager.GetString("PublishInstanceStatusReady", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing deployment for {0} with Subscription ID: {1}.... + /// + public static string PublishPreparingDeploymentMessage + { + get + { + return ResourceManager.GetString("PublishPreparingDeploymentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publishing {0} to Microsoft Azure. This may take several minutes.... + /// + public static string PublishServiceStartMessage + { + get + { + return ResourceManager.GetString("PublishServiceStartMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publish settings. + /// + public static string PublishSettings + { + get + { + return ResourceManager.GetString("PublishSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure. + /// + public static string PublishSettingsElementName + { + get + { + return ResourceManager.GetString("PublishSettingsElementName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to .PublishSettings. + /// + public static string PublishSettingsFileExtention + { + get + { + return ResourceManager.GetString("PublishSettingsFileExtention", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to publishSettings.xml. + /// + public static string PublishSettingsFileName + { + get + { + return ResourceManager.GetString("PublishSettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to &whr={0}. + /// + public static string PublishSettingsFileRealmFormat + { + get + { + return ResourceManager.GetString("PublishSettingsFileRealmFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Publish settings imported. + /// + public static string PublishSettingsSetSuccessfully + { + get + { + return ResourceManager.GetString("PublishSettingsSetSuccessfully", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AZURE_PUBLISHINGPROFILE_URL. + /// + public static string PublishSettingsUrlEnv + { + get + { + return ResourceManager.GetString("PublishSettingsUrlEnv", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting.... + /// + public static string PublishStartingMessage + { + get + { + return ResourceManager.GetString("PublishStartingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Upgrading.... + /// + public static string PublishUpgradingMessage + { + get + { + return ResourceManager.GetString("PublishUpgradingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Uploading Package to storage service {0}.... + /// + public static string PublishUploadingPackageMessage + { + get + { + return ResourceManager.GetString("PublishUploadingPackageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Verifying storage account '{0}'.... + /// + public static string PublishVerifyingStorageMessage + { + get + { + return ResourceManager.GetString("PublishVerifyingStorageMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionAdditionalContentPathNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionAdditionalContentPathNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration published to {0}. + /// + public static string PublishVMDscExtensionArchiveUploadedMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionArchiveUploadedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyFileVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyFileVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Copy the module '{0}' to '{1}'.. + /// + public static string PublishVMDscExtensionCopyModuleVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCopyModuleVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1).. + /// + public static string PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionCreateArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleted '{0}'. + /// + public static string PublishVMDscExtensionDeletedFileMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeletedFileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot delete '{0}': {1}. + /// + public static string PublishVMDscExtensionDeleteErrorMessage + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDeleteErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Path '{0}' not found.. + /// + public static string PublishVMDscExtensionDirectoryNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionDirectoryNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot get module for DscResource '{0}'. Possible solutions: + ///1) Specify -ModuleName for Import-DscResource in your configuration. + ///2) Unblock module that contains resource. + ///3) Move Import-DscResource inside Node block. + ///. + /// + public static string PublishVMDscExtensionGetDscResourceFailed + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionGetDscResourceFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to List of required modules: [{0}].. + /// + public static string PublishVMDscExtensionRequiredModulesVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredModulesVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version.. + /// + public static string PublishVMDscExtensionRequiredPsVersion + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionRequiredPsVersion", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration script '{0}' contained parse errors: + ///{1}. + /// + public static string PublishVMDscExtensionStorageParserErrors + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionStorageParserErrors", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Temp folder '{0}' created.. + /// + public static string PublishVMDscExtensionTempFolderVerbose + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionTempFolderVerbose", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid configuration file: {0}. + ///The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip).. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileInvalidExtension", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Configuration file '{0}' not found.. + /// + public static string PublishVMDscExtensionUploadArchiveConfigFileNotExist + { + get + { + return ResourceManager.GetString("PublishVMDscExtensionUploadArchiveConfigFileNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Azure PowerShell collects usage data in order to improve your experience. + ///The data is anonymous and does not include commandline argument values. + ///The data is collected by Microsoft. + /// + ///Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. + ///Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enab [rest of string was truncated]";. + /// + public static string RDFEDataCollectionMessage + { + get + { + return ResourceManager.GetString("RDFEDataCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Replace current deployment with '{0}' Id ?. + /// + public static string RedeployCommit + { + get + { + return ResourceManager.GetString("RedeployCommit", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to regenerate key?. + /// + public static string RegenerateKeyWarning + { + get + { + return ResourceManager.GetString("RegenerateKeyWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Generate new key.. + /// + public static string RegenerateKeyWhatIfMessage + { + get + { + return ResourceManager.GetString("RegenerateKeyWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove account '{0}'?. + /// + public static string RemoveAccountConfirmation + { + get + { + return ResourceManager.GetString("RemoveAccountConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing account. + /// + public static string RemoveAccountMessage + { + get + { + return ResourceManager.GetString("RemoveAccountMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove Add-On Confirmation. + /// + public static string RemoveAddOnConformation + { + get + { + return ResourceManager.GetString("RemoveAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm.. + /// + public static string RemoveAddOnMessage + { + get + { + return ResourceManager.GetString("RemoveAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureBGPPeering Operation failed.. + /// + public static string RemoveAzureBGPPeeringFailed + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Bgp Peering. + /// + public static string RemoveAzureBGPPeeringMessage + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Bgp Peering with Service Key {0}.. + /// + public static string RemoveAzureBGPPeeringSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Bgp Peering with service key '{0}'?. + /// + public static string RemoveAzureBGPPeeringWarning + { + get + { + return ResourceManager.GetString("RemoveAzureBGPPeeringWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit with service key '{0}'?. + /// + public static string RemoveAzureDedicatdCircuitWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatdCircuitWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuit Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureDedicatedCircuitLink Operation failed.. + /// + public static string RemoveAzureDedicatedCircuitLinkFailed + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circui Link. + /// + public static string RemoveAzureDedicatedCircuitLinkMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1}. + /// + public static string RemoveAzureDedicatedCircuitLinkSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'?. + /// + public static string RemoveAzureDedicatedCircuitLinkWarning + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitLinkWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing Dedicated Circuit. + /// + public static string RemoveAzureDedicatedCircuitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Azure Dedicated Circuit with Service Key {0}.. + /// + public static string RemoveAzureDedicatedCircuitSucceeded + { + get + { + return ResourceManager.GetString("RemoveAzureDedicatedCircuitSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing cloud service {0}.... + /// + public static string RemoveAzureServiceWaitMessage + { + get + { + return ResourceManager.GetString("RemoveAzureServiceWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription.. + /// + public static string RemoveDefaultSubscription + { + get + { + return ResourceManager.GetString("RemoveDefaultSubscription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing {0} deployment for {1} service. + /// + public static string RemoveDeploymentWaitMessage + { + get + { + return ResourceManager.GetString("RemoveDeploymentWaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'?. + /// + public static string RemoveEnvironmentConfirmation + { + get + { + return ResourceManager.GetString("RemoveEnvironmentConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing environment. + /// + public static string RemoveEnvironmentMessage + { + get + { + return ResourceManager.GetString("RemoveEnvironmentMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job collection. + /// + public static string RemoveJobCollectionMessage + { + get + { + return ResourceManager.GetString("RemoveJobCollectionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job collection "{0}". + /// + public static string RemoveJobCollectionWarning + { + get + { + return ResourceManager.GetString("RemoveJobCollectionWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing job. + /// + public static string RemoveJobMessage + { + get + { + return ResourceManager.GetString("RemoveJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the job "{0}". + /// + public static string RemoveJobWarning + { + get + { + return ResourceManager.GetString("RemoveJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the account?. + /// + public static string RemoveMediaAccountWarning + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account removed.. + /// + public static string RemoveMediaAccountWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveMediaAccountWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription.. + /// + public static string RemoveNamespaceErrorMessage + { + get + { + return ResourceManager.GetString("RemoveNamespaceErrorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing old package {0}.... + /// + public static string RemovePackage + { + get + { + return ResourceManager.GetString("RemovePackage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile?. + /// + public static string RemoveProfileConfirmation + { + get + { + return ResourceManager.GetString("RemoveProfileConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing the Azure profile. + /// + public static string RemoveProfileMessage + { + get + { + return ResourceManager.GetString("RemoveProfileMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the namespace '{0}'?. + /// + public static string RemoveServiceBusNamespaceConfirmation + { + get + { + return ResourceManager.GetString("RemoveServiceBusNamespaceConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove cloud service?. + /// + public static string RemoveServiceWarning + { + get + { + return ResourceManager.GetString("RemoveServiceWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove cloud service and all it's deployments. + /// + public static string RemoveServiceWhatIfMessage + { + get + { + return ResourceManager.GetString("RemoveServiceWhatIfMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove subscription '{0}'?. + /// + public static string RemoveSubscriptionConfirmation + { + get + { + return ResourceManager.GetString("RemoveSubscriptionConfirmation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing subscription. + /// + public static string RemoveSubscriptionMessage + { + get + { + return ResourceManager.GetString("RemoveSubscriptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The endpoint {0} cannot be removed from profile {1} because it's not in the profile.. + /// + public static string RemoveTrafficManagerEndpointMissing + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerEndpointMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Remove-AzureTrafficManagerProfile Operation failed.. + /// + public static string RemoveTrafficManagerProfileFailed + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Successfully removed Traffic Manager profile with name {0}.. + /// + public static string RemoveTrafficManagerProfileSucceeded + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileSucceeded", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the Traffic Manager profile "{0}"?. + /// + public static string RemoveTrafficManagerProfileWarning + { + get + { + return ResourceManager.GetString("RemoveTrafficManagerProfileWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to delete the VM '{0}'?. + /// + public static string RemoveVMConfirmationMessage + { + get + { + return ResourceManager.GetString("RemoveVMConfirmationMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting VM.. + /// + public static string RemoveVMMessage + { + get + { + return ResourceManager.GetString("RemoveVMMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing WebJob.... + /// + public static string RemoveWebJobMessage + { + get + { + return ResourceManager.GetString("RemoveWebJobMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove job '{0}'?. + /// + public static string RemoveWebJobWarning + { + get + { + return ResourceManager.GetString("RemoveWebJobWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing website. + /// + public static string RemoveWebsiteMessage + { + get + { + return ResourceManager.GetString("RemoveWebsiteMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to remove the website "{0}". + /// + public static string RemoveWebsiteWarning + { + get + { + return ResourceManager.GetString("RemoveWebsiteWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Removing public environment is not supported.. + /// + public static string RemovingDefaultEnvironmentsNotSupported + { + get + { + return ResourceManager.GetString("RemovingDefaultEnvironmentsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deleting namespace. + /// + public static string RemovingNamespaceMessage + { + get + { + return ResourceManager.GetString("RemovingNamespaceMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Repository is not setup. You need to pass a valid site name.. + /// + public static string RepositoryNotSetup + { + get + { + return ResourceManager.GetString("RepositoryNotSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use.. + /// + public static string ReservedIPNameNoLongerInUseButStillBeingReserved + { + get + { + return ResourceManager.GetString("ReservedIPNameNoLongerInUseButStillBeingReserved", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resource with ID : {0} does not exist.. + /// + public static string ResourceNotFound + { + get + { + return ResourceManager.GetString("ResourceNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Restart. + /// + public static string Restart + { + get + { + return ResourceManager.GetString("Restart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Resume. + /// + public static string Resume + { + get + { + return ResourceManager.GetString("Resume", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /role:{0};"{1}/{0}" . + /// + public static string RoleArgTemplate + { + get + { + return ResourceManager.GetString("RoleArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to bin. + /// + public static string RoleBinFolderName + { + get + { + return ResourceManager.GetString("RoleBinFolderName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} is {1}. + /// + public static string RoleInstanceWaitMsg + { + get + { + return ResourceManager.GetString("RoleInstanceWaitMsg", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 20. + /// + public static string RoleMaxInstances + { + get + { + return ResourceManager.GetString("RoleMaxInstances", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to role name. + /// + public static string RoleName + { + get + { + return ResourceManager.GetString("RoleName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided role name {0} doesn't exist. + /// + public static string RoleNotFoundMessage + { + get + { + return ResourceManager.GetString("RoleNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RoleSettings.xml. + /// + public static string RoleSettingsTemplateFileName + { + get + { + return ResourceManager.GetString("RoleSettingsTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role type {0} doesn't exist. + /// + public static string RoleTypeDoesNotExist + { + get + { + return ResourceManager.GetString("RoleTypeDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to public static Dictionary<string, Location> ReverseLocations { get; private set; }. + /// + public static string RuntimeDeploymentLocationError + { + get + { + return ResourceManager.GetString("RuntimeDeploymentLocationError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Preparing runtime deployment for service '{0}'. + /// + public static string RuntimeDeploymentStart + { + get + { + return ResourceManager.GetString("RuntimeDeploymentStart", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version?. + /// + public static string RuntimeMismatchWarning + { + get + { + return ResourceManager.GetString("RuntimeMismatchWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEOVERRIDEURL. + /// + public static string RuntimeOverrideKey + { + get + { + return ResourceManager.GetString("RuntimeOverrideKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /runtimemanifest/runtimes/runtime. + /// + public static string RuntimeQuery + { + get + { + return ResourceManager.GetString("RuntimeQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEID. + /// + public static string RuntimeTypeKey + { + get + { + return ResourceManager.GetString("RuntimeTypeKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEURL. + /// + public static string RuntimeUrlKey + { + get + { + return ResourceManager.GetString("RuntimeUrlKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to RUNTIMEVERSIONPRIMARYKEY. + /// + public static string RuntimeVersionPrimaryKey + { + get + { + return ResourceManager.GetString("RuntimeVersionPrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to scaffold.xml. + /// + public static string ScaffoldXml + { + get + { + return ResourceManager.GetString("ScaffoldXml", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation. + /// + public static string SchedulerInvalidLocation + { + get + { + return ResourceManager.GetString("SchedulerInvalidLocation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the Secondary Peer Subnet has to be provided.. + /// + public static string SecondaryPeerSubnetRequired + { + get + { + return ResourceManager.GetString("SecondaryPeerSubnetRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} already exists on disk in location {1}. + /// + public static string ServiceAlreadyExistsOnDisk + { + get + { + return ResourceManager.GetString("ServiceAlreadyExistsOnDisk", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No ServiceBus authorization rule with the given characteristics was found. + /// + public static string ServiceBusAuthorizationRuleNotFound + { + get + { + return ResourceManager.GetString("ServiceBusAuthorizationRuleNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The service bus entity '{0}' is not found.. + /// + public static string ServiceBusEntityTypeNotFound + { + get + { + return ResourceManager.GetString("ServiceBusEntityTypeNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Internal Server Error. This could happen due to an incorrect/missing namespace. + /// + public static string ServiceBusNamespaceMissingMessage + { + get + { + return ResourceManager.GetString("ServiceBusNamespaceMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service configuration. + /// + public static string ServiceConfiguration + { + get + { + return ResourceManager.GetString("ServiceConfiguration", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service definition. + /// + public static string ServiceDefinition + { + get + { + return ResourceManager.GetString("ServiceDefinition", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to ServiceDefinition.csdef. + /// + public static string ServiceDefinitionFileName + { + get + { + return ResourceManager.GetString("ServiceDefinitionFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0}Deploy. + /// + public static string ServiceDeploymentName + { + get + { + return ResourceManager.GetString("ServiceDeploymentName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The specified cloud service "{0}" does not exist.. + /// + public static string ServiceDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is in {2} state, please wait until it finish and update it's status. + /// + public static string ServiceIsInTransitionState + { + get + { + return ResourceManager.GetString("ServiceIsInTransitionState", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}.". + /// + public static string ServiceManagementClientExceptionStringFormat + { + get + { + return ResourceManager.GetString("ServiceManagementClientExceptionStringFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Begin Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSBeginOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSBeginOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Completed Operation: {0}. + /// + public static string ServiceManagementExecuteClientActionInOCSCompletedOperation + { + get + { + return ResourceManager.GetString("ServiceManagementExecuteClientActionInOCSCompletedOperation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service name. + /// + public static string ServiceName + { + get + { + return ResourceManager.GetString("ServiceName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provided service name {0} already exists, please pick another name. + /// + public static string ServiceNameExists + { + get + { + return ResourceManager.GetString("ServiceNameExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please provide name for the hosted service. + /// + public static string ServiceNameMissingMessage + { + get + { + return ResourceManager.GetString("ServiceNameMissingMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service parent directory. + /// + public static string ServiceParentDirectory + { + get + { + return ResourceManager.GetString("ServiceParentDirectory", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Service {0} removed successfully. + /// + public static string ServiceRemovedMessage + { + get + { + return ResourceManager.GetString("ServiceRemovedMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service directory. + /// + public static string ServiceRoot + { + get + { + return ResourceManager.GetString("ServiceRoot", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to service settings. + /// + public static string ServiceSettings + { + get + { + return ResourceManager.GetString("ServiceSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.. + /// + public static string ServiceSettings_ValidateStorageAccountName_InvalidName + { + get + { + return ResourceManager.GetString("ServiceSettings_ValidateStorageAccountName_InvalidName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The {0} slot for cloud service {1} doesn't exist.. + /// + public static string ServiceSlotDoesNotExist + { + get + { + return ResourceManager.GetString("ServiceSlotDoesNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} slot for service {1} is {2}. + /// + public static string ServiceStatusChanged + { + get + { + return ResourceManager.GetString("ServiceStatusChanged", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Set Add-On Confirmation. + /// + public static string SetAddOnConformation + { + get + { + return ResourceManager.GetString("SetAddOnConformation", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Profile {0} does not contain endpoint {1}. Adding it.. + /// + public static string SetInexistentTrafficManagerEndpointMessage + { + get + { + return ResourceManager.GetString("SetInexistentTrafficManagerEndpointMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my + ///contact information with {2}.. + /// + public static string SetMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Note - You will be charged the amount for the new plan, without being refunded for time remaining + ///in the existing plan. + ///By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis + ///for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) + ///acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of + ///use and privacy statement at <url> and (c) agree to sharing my contact information with {2}.. + /// + public static string SetNonMicrosoftAddOnMessage + { + get + { + return ResourceManager.GetString("SetNonMicrosoftAddOnMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Role {0} instances are set to {1}. + /// + public static string SetRoleInstancesMessage + { + get + { + return ResourceManager.GetString("SetRoleInstancesMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {"Slot":"","Location":"","Subscription":"","StorageAccountName":""}. + /// + public static string SettingsFileEmptyContent + { + get + { + return ResourceManager.GetString("SettingsFileEmptyContent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to deploymentSettings.json. + /// + public static string SettingsFileName + { + get + { + return ResourceManager.GetString("SettingsFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Insufficient parameters passed to create a new endpoint.. + /// + public static string SetTrafficManagerEndpointNeedsParameters + { + get + { + return ResourceManager.GetString("SetTrafficManagerEndpointNeedsParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ambiguous operation: the profile name specified doesn't match the name of the profile object.. + /// + public static string SetTrafficManagerProfileAmbiguous + { + get + { + return ResourceManager.GetString("SetTrafficManagerProfileAmbiguous", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts.. + /// + public static string ShouldContinueFail + { + get + { + return ResourceManager.GetString("ShouldContinueFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Confirm. + /// + public static string ShouldProcessCaption + { + get + { + return ResourceManager.GetString("ShouldProcessCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailConfirm + { + get + { + return ResourceManager.GetString("ShouldProcessFailConfirm", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again.. + /// + public static string ShouldProcessFailImpact + { + get + { + return ResourceManager.GetString("ShouldProcessFailImpact", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter.. + /// + public static string ShouldProcessFailWhatIf + { + get + { + return ResourceManager.GetString("ShouldProcessFailWhatIf", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Shutdown. + /// + public static string Shutdown + { + get + { + return ResourceManager.GetString("Shutdown", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to /sites:{0};{1};"{2}/{0}" . + /// + public static string SitesArgTemplate + { + get + { + return ResourceManager.GetString("SitesArgTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to 1000. + /// + public static string StandardRetryDelayInMs + { + get + { + return ResourceManager.GetString("StandardRetryDelayInMs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Start. + /// + public static string Start + { + get + { + return ResourceManager.GetString("Start", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Started. + /// + public static string StartedEmulator + { + get + { + return ResourceManager.GetString("StartedEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Starting Emulator.... + /// + public static string StartingEmulator + { + get + { + return ResourceManager.GetString("StartingEmulator", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to start. + /// + public static string StartStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StartStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stop. + /// + public static string Stop + { + get + { + return ResourceManager.GetString("Stop", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopping emulator.... + /// + public static string StopEmulatorMessage + { + get + { + return ResourceManager.GetString("StopEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Stopped. + /// + public static string StoppedEmulatorMessage + { + get + { + return ResourceManager.GetString("StoppedEmulatorMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to stop. + /// + public static string StopStorageEmulatorCommandArgument + { + get + { + return ResourceManager.GetString("StopStorageEmulatorCommandArgument", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Account Name:. + /// + public static string StorageAccountName + { + get + { + return ResourceManager.GetString("StorageAccountName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot find storage account '{0}' please type the name of an existing storage account.. + /// + public static string StorageAccountNotFound + { + get + { + return ResourceManager.GetString("StorageAccountNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to AzureStorageEmulator.exe. + /// + public static string StorageEmulatorExe + { + get + { + return ResourceManager.GetString("StorageEmulatorExe", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to InstallPath. + /// + public static string StorageEmulatorInstallPathRegistryKeyValue + { + get + { + return ResourceManager.GetString("StorageEmulatorInstallPathRegistryKeyValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to SOFTWARE\Microsoft\Windows Azure Storage Emulator. + /// + public static string StorageEmulatorRegistryKey + { + get + { + return ResourceManager.GetString("StorageEmulatorRegistryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Primary Key:. + /// + public static string StoragePrimaryKey + { + get + { + return ResourceManager.GetString("StoragePrimaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Secondary Key:. + /// + public static string StorageSecondaryKey + { + get + { + return ResourceManager.GetString("StorageSecondaryKey", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription named {0} already exists.. + /// + public static string SubscriptionAlreadyExists + { + get + { + return ResourceManager.GetString("SubscriptionAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information.. + /// + public static string SubscriptionDataFileDeprecated + { + get + { + return ResourceManager.GetString("SubscriptionDataFileDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to DefaultSubscriptionData.xml. + /// + public static string SubscriptionDataFileName + { + get + { + return ResourceManager.GetString("SubscriptionDataFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription data file {0} does not exist.. + /// + public static string SubscriptionDataFileNotFound + { + get + { + return ResourceManager.GetString("SubscriptionDataFileNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription id {0} doesn't exist.. + /// + public static string SubscriptionIdNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionIdNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription must not be null. + /// + public static string SubscriptionMustNotBeNull + { + get + { + return ResourceManager.GetString("SubscriptionMustNotBeNull", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription name needs to be specified.. + /// + public static string SubscriptionNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The subscription name {0} doesn't exist.. + /// + public static string SubscriptionNameNotFoundMessage + { + get + { + return ResourceManager.GetString("SubscriptionNameNotFoundMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Subscription needs to be specified.. + /// + public static string SubscriptionNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("SubscriptionNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Suspend. + /// + public static string Suspend + { + get + { + return ResourceManager.GetString("Suspend", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Swapping website production slot .... + /// + public static string SwappingWebsite + { + get + { + return ResourceManager.GetString("SwappingWebsite", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Are you sure you want to swap the website '{0}' production slot with slot '{1}'?. + /// + public static string SwapWebsiteSlotWarning + { + get + { + return ResourceManager.GetString("SwapWebsiteSlotWarning", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The Switch-AzureMode cmdlet is deprecated and will be removed in a future release.. + /// + public static string SwitchAzureModeDeprecated + { + get + { + return ResourceManager.GetString("SwitchAzureModeDeprecated", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}'. + /// + public static string TraceBeginLROJob + { + get + { + return ResourceManager.GetString("TraceBeginLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}'. + /// + public static string TraceBlockLROThread + { + get + { + return ResourceManager.GetString("TraceBlockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Completing cmdlet execution in RunJob. + /// + public static string TraceEndLROJob + { + get + { + return ResourceManager.GetString("TraceEndLROJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}'. + /// + public static string TraceHandleLROStateChange + { + get + { + return ResourceManager.GetString("TraceHandleLROStateChange", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job due to stoppage or failure. + /// + public static string TraceHandlerCancelJob + { + get + { + return ResourceManager.GetString("TraceHandlerCancelJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Unblocking job that was previously blocked.. + /// + public static string TraceHandlerUnblockJob + { + get + { + return ResourceManager.GetString("TraceHandlerUnblockJob", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Error in cmdlet execution. + /// + public static string TraceLROJobException + { + get + { + return ResourceManager.GetString("TraceLROJobException", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: Removing state changed event handler, exception '{0}'. + /// + public static string TraceRemoveLROEventHandler + { + get + { + return ResourceManager.GetString("TraceRemoveLROEventHandler", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to [AzureLongRunningJob]: ShouldMethod '{0}' unblocked.. + /// + public static string TraceUnblockLROThread + { + get + { + return ResourceManager.GetString("TraceUnblockLROThread", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}.. + /// + public static string UnableToDecodeBase64String + { + get + { + return ResourceManager.GetString("UnableToDecodeBase64String", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unable to update mismatching Json structured: {0} {1}.. + /// + public static string UnableToPatchJson + { + get + { + return ResourceManager.GetString("UnableToPatchJson", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The provider {0} is unknown.. + /// + public static string UnknownProviderMessage + { + get + { + return ResourceManager.GetString("UnknownProviderMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Update. + /// + public static string Update + { + get + { + return ResourceManager.GetString("Update", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Updated settings for subscription '{0}'. Current subscription is '{1}'.. + /// + public static string UpdatedSettings + { + get + { + return ResourceManager.GetString("UpdatedSettings", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name is not valid.. + /// + public static string UserNameIsNotValid + { + get + { + return ResourceManager.GetString("UserNameIsNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User name needs to be specified.. + /// + public static string UserNameNeedsToBeSpecified + { + get + { + return ResourceManager.GetString("UserNameNeedsToBeSpecified", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A value for the VLan Id has to be provided.. + /// + public static string VlanIdRequired + { + get + { + return ResourceManager.GetString("VlanIdRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Please wait.... + /// + public static string WaitMessage + { + get + { + return ResourceManager.GetString("WaitMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The azure storage emulator is not installed, skip launching.... + /// + public static string WarningWhenStorageEmulatorIsMissing + { + get + { + return ResourceManager.GetString("WarningWhenStorageEmulatorIsMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Web.cloud.config. + /// + public static string WebCloudConfig + { + get + { + return ResourceManager.GetString("WebCloudConfig", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to web.config. + /// + public static string WebConfigTemplateFileName + { + get + { + return ResourceManager.GetString("WebConfigTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to MSDeploy. + /// + public static string WebDeployKeywordInWebSitePublishProfile + { + get + { + return ResourceManager.GetString("WebDeployKeywordInWebSitePublishProfile", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot build the project successfully. Please see logs in {0}.. + /// + public static string WebProjectBuildFailTemplate + { + get + { + return ResourceManager.GetString("WebProjectBuildFailTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole. + /// + public static string WebRole + { + get + { + return ResourceManager.GetString("WebRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_web.cmd > log.txt. + /// + public static string WebRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WebRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebRole.xml. + /// + public static string WebRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WebRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Webspace.. + /// + public static string WebsiteAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WebSite with given name {0} already exists in the specified Subscription and Location.. + /// + public static string WebsiteAlreadyExistsReplacement + { + get + { + return ResourceManager.GetString("WebsiteAlreadyExistsReplacement", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Site {0} already has repository created for it.. + /// + public static string WebsiteRepositoryAlreadyExists + { + get + { + return ResourceManager.GetString("WebsiteRepositoryAlreadyExists", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Workspaces/WebsiteExtension/Website/{0}/dashboard/. + /// + public static string WebsiteSufixUrl + { + get + { + return ResourceManager.GetString("WebsiteSufixUrl", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to https://{0}/msdeploy.axd?site={1}. + /// + public static string WebSiteWebDeployUriTemplate + { + get + { + return ResourceManager.GetString("WebSiteWebDeployUriTemplate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole. + /// + public static string WorkerRole + { + get + { + return ResourceManager.GetString("WorkerRole", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to setup_worker.cmd > log.txt. + /// + public static string WorkerRoleStartupTaskCommandLine + { + get + { + return ResourceManager.GetString("WorkerRoleStartupTaskCommandLine", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to WorkerRole.xml. + /// + public static string WorkerRoleTemplateFileName + { + get + { + return ResourceManager.GetString("WorkerRoleTemplateFileName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to (x86). + /// + public static string x86InProgramFiles + { + get + { + return ResourceManager.GetString("x86InProgramFiles", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes. + /// + public static string Yes + { + get + { + return ResourceManager.GetString("Yes", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Yes, I agree. + /// + public static string YesHint + { + get + { + return ResourceManager.GetString("YesHint", resourceCulture); + } + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.resx b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.resx new file mode 100644 index 00000000000..a08a2e50172 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Properties/Resources.resx @@ -0,0 +1,1747 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The remote server returned an error: (401) Unauthorized. + + + Account "{0}" has been added. + + + To switch to a different subscription, please use Select-AzureSubscription. + + + Subscription "{0}" is selected as the default subscription. + + + To view all the subscriptions, please use Get-AzureSubscription. + + + Add-On {0} is created successfully. + + + Add-on name {0} is already used. + + + Add-On {0} not found. + + + Add-on {0} is removed successfully. + + + Add-On {0} is updated successfully. + + + Role has been created at {0}\{1}. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for Node.js by running ‘npm install azure’. + + + Role has been created at {0}\{1}. For easy access to Microsoft Azure services from your application code, install the Microsoft Azure client library for PHP by running "pear WindowsAzure/WindowsAzure". + + + Unable to set role permissions. Please give the 'Network Service' user 'Read & execute' and 'Modify' permissions to the role folder, or run PowerShell as an Administrator + + + A role name '{0}' already exists + + + Windows Azure Powershell\ + + + https://manage.windowsazure.com + + + AZURE_PORTAL_URL + + + Azure SDK\{0}\ + + + Base Uri was empty. + WAPackIaaS + + + {0} begin processing without ParameterSet. + + + {0} begin processing with ParameterSet '{1}'. + + + Blob with the name {0} already exists in the account. + + + https://{0}.blob.core.windows.net/ + + + AZURE_BLOBSTORAGE_TEMPLATE + + + CACHERUNTIMEURL + + + cache + + + CacheRuntimeVersion + + + Installing caching version {0} for Role '{1}' (the caching version locally installed is: {2}) + + + Cannot find {0} with name {1}. + + + Deployment for service {0} with {1} slot doesn't exist + + + Can't find valid Microsoft Azure role in current directory {0} + + + service {0} configuration file (ServiceConfiguration.Cloud.cscfg) is either null or doesn't exist + + + Invalid service path! Cannot locate ServiceDefinition.csdef in current folder or parent folders. + + + The subscription named {0} with id {1} is not currently imported. You must import this subscription before it can be updated. + + + ManagementCertificate + + + certificate.pfx + + + Certificate imported into CurrentUser\My\{0} + + + Your account does not have access to the private key for certificate {0} + + + {0} {1} deployment for {2} service + + + Cloud service {0} is in {1} state. + + + Changing/Removing public environment '{0}' is not allowed. + + + Service {0} is set to value {1} + + + Choose which publish settings file to use: + + + Microsoft.WindowsAzure.Plugins.Caching.ClientDiagnosticLevel + + + 1 + + + cloud_package.cspkg + + + ServiceConfiguration.Cloud.cscfg + + + Add-ons for {0} + + + Communication could not be established. This could be due to an invalid subscription ID. Note that subscription IDs are case sensitive. + + + Complete + + + config.json + + + VirtualMachine creation failed. + WAPackIaaS + + + Creating the website failed. If this is the first website for this subscription, please create it using the management portal instead. + + + Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core + + + //blobcontainer[@datacenter='{0}'] + + + Setting: {0} as the default and current subscription. To view other subscriptions use Get-AzureSubscription + + + none + + + There are no hostnames which could be used for validation. + + + 8080 + + + 1000 + + + Auto + + + 80 + + + Delete + WAPackIaaS + + + The {0} slot for service {1} is already in {2} state + + + The deployment in {0} slot for service {1} is removed + + + Microsoft.WindowsAzure.Plugins.Caching.DiagnosticLevel + + + 1 + + + The key to add already exists in the dictionary. + + + The array index cannot be less than zero. + + + The supplied array does not have enough room to contain the copied elements. + + + The provided dns {0} doesn't exist + + + Microsoft Azure Certificate + + + Endpoint can't be retrieved for storage account + + + {0} end processing. + + + To use Active Directory authentication, you must configure the ActiveDirectoryEndpoint, ActiveDirectoryTenantId, and ActiveDirectorServiceEndpointResourceId for environment of '{0}'. You can configure these properties for this environment using the Set-AzureEnvironment cmdlet. + + + The environment '{0}' already exists. + + + environments.xml + + + Error creating VirtualMachine + WAPackIaaS + + + Unable to download available runtimes for location '{0}' + + + Error updating VirtualMachine + WAPackIaaS + + + Job Id {0} failed. Error: {1}, ExceptionDetails: {2} + WAPackIaaS + + + The HTTP request was forbidden with client authentication scheme 'Anonymous'. + + + This add-on requires you to purchase the first instance through the Microsoft Azure Portal. Subsequent purchases can be performed through PowerShell. + + + Operation Status: + + + Resources\Scaffolding\General + + + Getting all available Microsoft Azure Add-Ons, this may take few minutes... + + + Name{0}Primary Key{0}Seconday Key + + + Git not found. Please install git and place it in your command line path. + + + Could not find publish settings. Please run Import-AzurePublishSettingsFile. + + + iisnode.dll + + + iisnode + + + iisnode-dev\\release\\x64 + + + iisnode + + + Installing IISNode version {0} in Azure for WebRole '{1}' (the version locally installed is: {2}) + + + Internal Server Error + + + Cannot enable memcach protocol on a cache worker role {0}. + + + Invalid certificate format. + + + The provided configuration path is invalid or doesn't exist + + + The country name is invalid, please use a valid two character country code, as described in ISO 3166-1 alpha-2. + + + Deployment with {0} does not exist + + + The deployment slot name {0} is invalid. Slot name must be either "Staging" or "Production". + + + Invalid service endpoint. + + + File {0} has invalid characters + + + You must create your git publishing credentials using the Microsoft Azure portal. +Please follow these steps in the portal: +1. On the left side open "Web Sites" +2. Click on any website +3. Choose "Setup Git Publishing" or "Reset deployment credentials" +4. Back in the PowerShell window, rerun this command by typing "New-AzureWebSite {site name} -Git -PublishingUsername {username} + + + The value {0} provided is not a valid GUID. Please provide a valid GUID. + + + The specified hostname does not exist. Please specify a valid hostname for the site. + + + Role {0} instances must be greater than or equal 0 and less than or equal 20 + + + There was an error creating your webjob. Please make sure that the script is in the root folder of the zip file. + + + Could not download a valid runtime manifest, Please check your internet connection and try again. + + + The account {0} was not found. Please specify a valid account name. + + + The provided name "{0}" does not match the service bus namespace naming rules. + + + Value cannot be null. Parameter name: '{0}' + + + The provided package path is invalid or doesn't exist + + + '{0}' is an invalid parameter set name. + + + {0} doesn't exist in {1} or you've not passed valid value for it + + + Path {0} has invalid characters + + + The provided publish settings file {0} has invalid content. Please get valid by running cmdlet Get-AzurePublishSettingsFile + + + The provided role name "{0}" has invalid characters + + + A valid name for the service root folder is required + + + {0} is not a recognized runtime type + + + A valid language is required + + + No subscription is currently selected. Use Select-Subscription to activate a subscription. + + + The provided location "{0}" does not exist in the available locations use Get-AzureSBLocation for listing available locations. + + + Please provide a service name or run this command from inside a service project directory. + + + You must provide valid value for {0} + + + settings.json is invalid or doesn't exist + + + The subscription named '{0}' cannot be found. Use Set-AzureSubscription to initialize the subscription data. + + + The provided subscription id {0} is not valid + + + A valid subscription name is required. This can be provided using the -Subscription parameter or by setting the subscription via the Set-AzureSubscription cmdlet + + + The provided subscriptions file {0} has invalid content. + + + Role {0} VM size should be ExtraSmall, Small, Medium, Large or ExtraLarge. + + + The web job file must have *.zip extension + + + Singleton option works for continuous jobs only. + + + The website {0} was not found. Please specify a valid website name. + + + No job for id: {0} was found. + WAPackIaaS + + + engines + + + Scaffolding for this language is not yet supported + + + Link already established + + + local_package.csx + + + ServiceConfiguration.Local.cscfg + + + Looking for {0} deployment for {1} cloud service... + + + Looking for cloud service {0}... + + + managementCertificate.pem + + + ?whr={0} + + + //baseuri + + + uri + + + http://az413943.vo.msecnd.net/node/runtimemanifest_0.7.5.2.xml + + + Multiple Add-Ons found holding name {0} + + + Multiple possible publishing users. Please go to the Portal and use the listed deployment user, or click 'set/reset deployment credentials' to set up a new user account, then reurn this cmdlet and specify PublishingUsername. + + + The first publish settings file "{0}" is used. If you want to use another file specify the file name. + + + Microsoft.WindowsAzure.Plugins.Caching.NamedCaches + + + {"caches":[{"name":"default","policy":{"eviction":{"type":0},"expiration":{"defaultTTL":10,"isExpirable":true,"type":1},"serverNotification":{"isEnabled":false}},"secondaries":0}]} + + + A publishing username is required. Please specify one using the argument PublishingUsername. + + + New Add-On Confirmation + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Internal Server Error. This could happen because the namespace name is already used or due to an incorrect location name. Use Get-AzureSBLocation cmdlet to list valid names. + + + By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at {0} and (c) agree to sharing my contact information with {2}. + + + Service has been created at {0} + + + No + + + There is no access token cached for subscription {0}, user id {1}. Use the Add-AzureAccount cmdlet to log in again and get a token for this subscription. + + + The service does not have any cache worker roles, add one first by running cmdlet Add-AzureCacheWorkerRole. + + + No clouds available + WAPackIaaS + + + nodejs + + + node + + + node.exe + + + There is no default subscription set, please set a default subscription by running Set-AzureSubscription -Default <subscription name> + + + Microsoft SDKs\Azure\Nodejs\Nov2011 + + + nodejs + + + node + + + Resources\Scaffolding\Node + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.Node + + + Installing Node version {0} in Azure for Role '{1}' (the Node version locally installed is: {2}) + + + No, I do not agree + + + No publish settings files with extension *.publishsettings are found in the directory "{0}". + + + '{0}' must be a cache worker role. Verify that it has proper cache worker role configuration. + + + Certificate can't be null. + + + {0} could not be null or empty + + + Unable to add a null RoleSettings to {0} + + + Unable to add new role to null service definition + + + The request offer '{0}' is not found. + + + Operation "{0}" failed on VM with ID: {1} + WAPackIaaS + + + The REST operation failed with message '{0}' and error code '{1}' + + + Job Id {0} did not complete within expected time or it is in Failed/Canceled/Invalid state. + WAPackIaaS + + + package + + + Package is created at service root path {0}. + + + {{ + "author": "", + + "name": "{0}", + "version": "0.0.0", + "dependencies":{{}}, + "devDependencies":{{}}, + "optionalDependencies": {{}}, + "engines": {{ + "node": "*", + "iisnode": "*" + }} + +}} + + + + package.json + + + A value for the Peer Asn has to be provided. + + + 5.4.0 + + + php + + + Resources\Scaffolding\PHP + + + Microsoft.WindowsAzure.Commands.CloudService.ScaffoldingResources.PHP + + + Installing PHP version {0} for Role '{1}' (the PHP version locally installed is: {2}) + + + You must create your first web site using the Microsoft Azure portal. +Please follow these steps in the portal: +1. At the bottom of the page, click on New > Web Site > Quick Create +2. Type {0} in the URL field +3. Click on "Create Web Site" +4. Once the site has been created, click on the site name +5. Click on "Set up Git publishing" or "Reset deployment credentials" and setup a publishing username and password. Use those credentials for all new websites you create. + + + 6. Back in the console window, rerun this command by typing "New-AzureWebsite <site name> -Git" + + + A value for the Primary Peer Subnet has to be provided. + + + Promotion code can be used only when updating to a new plan. + + + Service not published at user request. + + + Complete. + + + Connecting... + + + Created Deployment ID: {0}. + + + Created hosted service '{0}'. + + + Created Website URL: {0}. + + + Creating... + + + Initializing... + + + busy + + + creating the virtual machine + + + Instance {0} of role {1} is {2}. + + + ready + + + Preparing deployment for {0} with Subscription ID: {1}... + + + Publishing {0} to Microsoft Azure. This may take several minutes... + + + publish settings + + + Azure + + + .PublishSettings + + + publishSettings.xml + + + Publish settings imported + + + AZURE_PUBLISHINGPROFILE_URL + + + Starting... + + + Upgrading... + + + Uploading Package to storage service {0}... + + + Verifying storage account '{0}'... + + + Replace current deployment with '{0}' Id ? + + + Are you sure you want to regenerate key? + + + Generate new key. + + + Are you sure you want to remove account '{0}'? + + + Removing account + + + Remove Add-On Confirmation + + + If you delete this add-on, your data may be deleted and the operation may not be undone. You may have to purchase it again from the Microsoft Azure Store to use it. The price of the add-on may not be refunded. Are you sure you want to delete this add-on? Enter “Yes” to confirm. + + + Remove-AzureBGPPeering Operation failed. + + + Removing Bgp Peering + + + Successfully removed Azure Bgp Peering with Service Key {0}. + + + Are you sure you want to remove the Bgp Peering with service key '{0}'? + + + Are you sure you want to remove the Dedicated Circuit with service key '{0}'? + + + Remove-AzureDedicatedCircuit Operation failed. + + + Remove-AzureDedicatedCircuitLink Operation failed. + + + Removing Dedicated Circui Link + + + Successfully removed Azure Dedicated Circuit Link with Service Key {0} and Vnet Name {1} + + + Are you sure you want to remove the Dedicated Circuit Link with service key '{0}' and virtual network name '{1}'? + + + Removing Dedicated Circuit + + + Successfully removed Azure Dedicated Circuit with Service Key {0}. + + + Removing cloud service {0}... + + + Removing {0} deployment for {1} service + + + Removing job collection + + + Are you sure you want to remove the job collection "{0}" + + + Removing job + + + Are you sure you want to remove the job "{0}" + + + Are you sure you want to remove the account? + + + Account removed. + + + Internal Server Error. This could happen because the namespace does not exist or it does not exist under your subscription. + + + Removing old package {0}... + + + Are you sure you want to delete the namespace '{0}'? + + + Are you sure you want to remove cloud service? + + + Remove cloud service and all it's deployments + + + Are you sure you want to remove subscription '{0}'? + + + Removing subscription + + + Are you sure you want to delete the VM '{0}'? + + + Deleting VM. + + + Removing WebJob... + + + Are you sure you want to remove job '{0}'? + + + Removing website + + + Are you sure you want to remove the website "{0}" + + + Deleting namespace + + + Repository is not setup. You need to pass a valid site name. + + + Reserved IP with the Name:'{0}' will no longer be in use after the deployment is deleted, and it is still reserved for later use. + + + Resource with ID : {0} does not exist. + WAPackIaaS + + + Restart + WAPackIaaS + + + Resume + WAPackIaaS + + + /role:{0};"{1}/{0}" + + + bin + + + Role {0} is {1} + + + 20 + + + role name + + + The provided role name {0} doesn't exist + + + RoleSettings.xml + + + Role type {0} doesn't exist + + + public static Dictionary<string, Location> ReverseLocations { get; private set; } + + + Preparing runtime deployment for service '{0}' + + + WARNING Runtime Mismatch: Are you sure that you want to publish service '{0}' using an Azure runtime version that does not match your local runtime version? + + + RUNTIMEOVERRIDEURL + + + /runtimemanifest/runtimes/runtime + + + RUNTIMEID + + + RUNTIMEURL + + + RUNTIMEVERSIONPRIMARYKEY + + + scaffold.xml + + + Invalid location entered. Pick one of the locations from Get-AzureSchedulerLocation + + + A value for the Secondary Peer Subnet has to be provided. + + + Service {0} already exists on disk in location {1} + + + No ServiceBus authorization rule with the given characteristics was found + + + The service bus entity '{0}' is not found. + + + Internal Server Error. This could happen due to an incorrect/missing namespace + + + service configuration + + + service definition + + + ServiceDefinition.csdef + + + {0}Deploy + + + The specified cloud service "{0}" does not exist. + + + {0} slot for service {1} is in {2} state, please wait until it finish and update it's status + + + Begin Operation: {0} + + + Completed Operation: {0} + + + Begin Operation: {0} + + + Completed Operation: {0} + + + service name + + + Please provide name for the hosted service + + + service parent directory + + + Service {0} removed successfully + + + service directory + + + service settings + + + The storage account name '{0}' is invalid. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. + + + The {0} slot for cloud service {1} doesn't exist. + + + {0} slot for service {1} is {2} + + + Set Add-On Confirmation + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +agree to the {2}'s terms of user and privacy statement at {0} and (c) agree to sharing my +contact information with {2}. + + + Note - You will be charged the amount for the new plan, without being refunded for time remaining +in the existing plan. +By typing "Yes", I (a) authorize Microsoft to charge my current payment method on a monthly basis +for the amount indicated at {0} for {1} until my service is cancelled or terminated, and (b) +acknowledge the offering is provided by {2}, not Microsoft, and agree to {2}'s terms of +use and privacy statement at <url> and (c) agree to sharing my contact information with {2}. + + + Role {0} instances are set to {1} + + + {"Slot":"","Location":"","Subscription":"","StorageAccountName":""} + + + deploymentSettings.json + + + Confirm + + + Shutdown + WAPackIaaS + + + /sites:{0};{1};"{2}/{0}" + + + 1000 + + + Start + WAPackIaaS + + + Started + + + Starting Emulator... + + + start + + + Stop + WAPackIaaS + + + Stopping emulator... + + + Stopped + + + stop + + + Account Name: + + + Cannot find storage account '{0}' please type the name of an existing storage account. + + + AzureStorageEmulator.exe + + + InstallPath + + + SOFTWARE\Microsoft\Windows Azure Storage Emulator + + + Primary Key: + + + Secondary Key: + + + The subscription named {0} already exists. + + + DefaultSubscriptionData.xml + + + The subscription data file {0} does not exist. + + + Subscription must not be null + WAPackIaaS + + + Suspend + WAPackIaaS + + + Swapping website production slot ... + + + Are you sure you want to swap the website '{0}' production slot with slot '{1}'? + + + The provider {0} is unknown. + + + Update + WAPackIaaS + + + Updated settings for subscription '{0}'. Current subscription is '{1}'. + + + A value for the VLan Id has to be provided. + + + Please wait... + + + The azure storage emulator is not installed, skip launching... + + + Web.cloud.config + + + web.config + + + MSDeploy + + + Cannot build the project successfully. Please see logs in {0}. + + + WebRole + + + setup_web.cmd > log.txt + + + WebRole.xml + + + WebSite with given name {0} already exists in the specified Subscription and Webspace. + + + WebSite with given name {0} already exists in the specified Subscription and Location. + + + Site {0} already has repository created for it. + + + Workspaces/WebsiteExtension/Website/{0}/dashboard/ + + + https://{0}/msdeploy.axd?site={1} + + + WorkerRole + + + setup_worker.cmd > log.txt + + + WorkerRole.xml + + + Yes + + + Yes, I agree + + + Remove-AzureTrafficManagerProfile Operation failed. + + + Successfully removed Traffic Manager profile with name {0}. + + + Are you sure you want to remove the Traffic Manager profile "{0}"? + + + Profile {0} already has an endpoint with name {1} + + + Profile {0} does not contain endpoint {1}. Adding it. + + + The endpoint {0} cannot be removed from profile {1} because it's not in the profile. + + + Insufficient parameters passed to create a new endpoint. + + + Ambiguous operation: the profile name specified doesn't match the name of the profile object. + + + <NONE> + + + "An exception occurred when calling the ServiceManagement API. HTTP Status Code: {0}. Service Management Error Code: {1}. Message: {2}. Operation Tracking ID: {3}." + {0} is the HTTP status code. {1} is the Service Management Error Code. {2} is the Service Management Error message. {3} is the operation tracking ID. + + + Unable to decode string from base 64. Please make sure the string is correctly encoded: {0}. + {0} is the string that is not in a valid base 64 format. + + + Skipping external tenant {0}, because you are using a guest or a foreign principal object identity. In order to access this tenant, please run Add-AzureAccount without "-Credential". + + + Removing an environment will remove all associated subscriptions and accounts. Are you sure you want to remove an environment '{0}'? + + + Removing environment + + + There is no subscription associated with account {0}. + + + Account id doesn't match one in subscription. + + + Environment name doesn't match one in subscription. + + + Removing the Azure profile will remove all associated environments, subscriptions, and accounts. Are you sure you want to remove the Azure profile? + + + Removing the Azure profile + + + The SubscriptionDataFile parameter is deprecated. This parameter will be removed in a future release. See https://github.com/Azure/azure-powershell/wiki/Proposed-Design-Stateless-Azure-Profile for a description of the upcoming mechanism for providing alternate sources of subscription information. + + + Account needs to be specified + + + No default subscription has been designated. Use Select-AzureSubscription -Default <subscriptionName> to set the default subscription. + + + Path must specify a valid path to an Azure profile. + + + Property bag Hashtable must contain one of the following sets of properties: {SubscriptionId, Certificate}, {SubscriptionId, Username, Password}, {SubscriptionId, ServicePrincipal, Password, Tenant}, {SubscriptionId, AccountId, Token} + + + Property bag Hashtable must contain a 'Certificate' of type 'X509Certificate2'. + + + Property bag Hashtable must contain a 'Password' with an associated 'Username' or 'ServicePrincipal'. + + + Property bag Hashtable must contain a 'SubscriptionId'. + + + Selected profile must not be null. + + + The Switch-AzureMode cmdlet is deprecated and will be removed in a future release. + + + OperationID : '{0}' + + + Cannot get module for DscResource '{0}'. Possible solutions: +1) Specify -ModuleName for Import-DscResource in your configuration. +2) Unblock module that contains resource. +3) Move Import-DscResource inside Node block. + + 0 = name of DscResource + + + Your current PowerShell version {1} is less then required by this cmdlet {0}. Consider download and install latest PowerShell version. + {0} = minimal required PS version, {1} = current PS version + + + Parsing configuration script: {0} + {0} is the path to a script file + + + Configuration script '{0}' contained parse errors: +{1} + 0 = path to the configuration script, 1 = parser errors + + + List of required modules: [{0}]. + {0} = list of modules + + + Temp folder '{0}' created. + {0} = temp folder path + + + Copy '{0}' to '{1}'. + {0} = source, {1} = destination + + + Copy the module '{0}' to '{1}'. + {0} = source, {1} = destination + + + File '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the path to a file + + + Configuration file '{0}' not found. + 0 = path to the configuration file + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Path '{0}' not found. + 0 = path to the additional content file/directory + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1) or a ZIP archive (.zip). + 0 = path to the configuration file + + + Invalid configuration file: {0}. +The file needs to be a PowerShell script (.ps1 or .psm1). + 0 = path to the configuration file + + + Create Archive + + + Upload '{0}' + {0} is the name of an storage blob + + + Storage Blob '{0}' already exists. Use the -Force parameter to overwrite it. + {0} is the name of an storage blob + + + Configuration published to {0} + {0} is an URI + + + Deleted '{0}' + {0} is the path of a file + + + Cannot delete '{0}': {1} + {0} is the path of a file, {1} is an error message + + + Cannot find the WadCfg end element in the config. + + + WadCfg start element in the config is not matching the end element. + + + Cannot find the WadCfg element in the config. + + + Cannot find configuration data file: {0} + + + The configuration data must be a .psd1 file + + + Cannot change built-in environment {0}. + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Az.Accounts module. To disable data collection: PS > Disable-AzDataCollection. +Use the Enable-AzDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Az.Accounts module. To enable data collection: PS > Enable-AzDataCollection. + + + Microsoft Azure PowerShell Data Collection Confirmation + + + You choose not to participate in Microsoft Azure PowerShell data collection. + + + This confirmation message will be dismissed in '{0}' second(s)... + + + You choose to participate in Microsoft Azure PowerShell data collection. + + + The setting profile has been saved to the following path '{0}'. + + + [Common.Authentication]: Authenticating for account {0} with single tenant {1}. + + + Changing public environment is not supported. + + + Environment name needs to be specified. + + + Environment needs to be specified. + + + The environment name '{0}' is not found. + + + File path is not valid. + + + Must specify a non-null subscription name. + + + The default subscription is being removed. Use Select-AzureSubscription -Default <subscriptionName> to select a new default subscription. + + + Removing public environment is not supported. + + + The subscription id {0} doesn't exist. + + + Subscription name needs to be specified. + + + The subscription name {0} doesn't exist. + + + Subscription needs to be specified. + + + User name is not valid. + + + User name needs to be specified. + + + "There is no current context, please log in using Connect-AzAccount." + + + No subscriptions are associated with the logged in account in Azure Service Management (RDFE). This means that the logged in user is not an administrator or co-administrator for any account.\r\nDid you mean to execute Connect-AzAccount? + + + No certificate was found in the certificate store with thumbprint {0} + + + Illegal characters in path. + + + Invalid certificate format. Publish settings may be corrupted. Use Get-AzurePublishSettingsFile to download updated settings + + + "{0}" is an invalid DNS name for {1} + + + The provided file in {0} must be have {1} extension + + + {0} is invalid or empty + + + Please connect to internet before executing this cmdlet + + + Path {0} doesn't exist. + + + Path for {0} doesn't exist in {1}. + + + &whr={0} + + + The provided service name {0} already exists, please pick another name + + + Unable to update mismatching Json structured: {0} {1}. + + + (x86) + + + Azure PowerShell collects usage data in order to improve your experience. +The data is anonymous and does not include commandline argument values. +The data is collected by Microsoft. + +Use the Disable-AzureDataCollection cmdlet to turn the feature Off. The cmdlet can be found in the Azure module. To disable data collection: PS > Disable-AzureDataCollection. +Use the Enable-AzureDataCollection cmdlet to turn the feature On. The cmdlet can be found in the Azure module. To enable data collection: PS > Enable-AzureDataCollection. + + + Execution failed because a background thread could not prompt the user. + + + Azure Long-Running Job + + + The cmdlet failed in background execution. The returned error was '{0}'. Please execute the cmdlet again. You may need to execute this cmdlet synchronously, by omitting the '-AsJob' parameter. + 0(string): exception message in background task + + + Please execute the cmdlet again and include the 'Force' parameter, if available, to avoid unnecessary prompts. + + + Please execute the cmdlet again and omit the 'Confirm' parameter when using the 'AsJob' parameter. + + + Please increase the user $ConfirmPreference setting, or include turn off confirmation using '-Confirm:$false' when using the 'AsJob' parameter and execute the cmdet again. + + + Please execute the cmdlet again and omit the 'WhatIf' parameter when using the 'AsJob' parameter. + + + [AzureLongRunningJob]: Starting cmdlet execution, setting for cmdlet confirmation required: '{0}' + 0(bool): whether cmdlet confirmation is required + + + [AzureLongRunningJob]: Blocking job for ShouldMethod '{0}' + 0(string): method type + + + [AzureLongRunningJob]: Completing cmdlet execution in RunJob + + + [AzureLongRunningJob]: State change from '{0}' to '{1}' because '{2}' + 0(string): last state, 1(string): new state, 2(string): state change reason + + + [AzureLongRunningJob]: Unblocking job due to stoppage or failure + + + [AzureLongRunningJob]: Unblocking job that was previously blocked. + + + [AzureLongRunningJob]: Error in cmdlet execution + + + [AzureLongRunningJob]: Removing state changed event handler, exception '{0}' + 0(string): exception message + + + [AzureLongRunningJob]: ShouldMethod '{0}' unblocked. + 0(string): methodType + + + +- The parameter : '{0}' is changing. + + + +- The parameter : '{0}' is becoming mandatory. + + + +- The parameter : '{0}' is being replaced by parameter : '{1}'. + + + +- The parameter : '{0}' is being replaced by mandatory parameter : '{1}'. + + + +- Change description : {0} + + + The cmdlet is being deprecated. There will be no replacement for it. + + + The cmdlet parameter set is being deprecated. There will be no replacement for it. + + + The cmdlet '{0}' is replacing this cmdlet. + + + +- The output type is changing from the existing type :'{0}' to the new type :'{1}' + + + +- The output type '{0}' is changing + + + +- The following properties are being added to the output type : + + + +- The following properties in the output type are being deprecated : + + + {0} + + + +- Cmdlet : '{0}' + - {1} + + + Upcoming breaking changes in the cmdlet '{0}' : + + + +- This change will take effect on '{0}' + + + +- The change is expected to take effect from version : '{0}' + + + ```powershell +# Old +{0} + +# New +{1} +``` + + + + +Cmdlet invocation changes : + Old Way : {0} + New Way : {1} + + + +The output type '{0}' is being deprecated without a replacement. + + + +The type of the parameter is changing from '{0}' to '{1}'. + + + +Note : Go to {0} for steps to suppress this breaking change warning, and other information on breaking changes in Azure PowerShell. + + + This cmdlet is in preview. Its behavior is subject to change based on customer feedback. + + + The estimated generally available date is '{0}'. + + + - The change is expected to take effect from Az version : '{0}' + + \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Response.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Response.cs new file mode 100644 index 00000000000..5bc3bc030b5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/JsonSerializer.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/JsonSerializer.cs new file mode 100644 index 00000000000..19c2deee27b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/PropertyTransformation.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/PropertyTransformation.cs new file mode 100644 index 00000000000..f4db4ec9368 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/SerializationOptions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Serialization/SerializationOptions.cs new file mode 100644 index 00000000000..def664a0092 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/SerializationMode.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/SerializationMode.cs new file mode 100644 index 00000000000..3f209b19a6b --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/SerializationMode.cs @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + [System.Flags] + public enum SerializationMode + { + None = 0, + IncludeHeaders = 1 << 0, + IncludeRead = 1 << 1, + IncludeCreate = 1 << 2, + IncludeUpdate = 1 << 3, + IncludeAll = IncludeHeaders | IncludeRead | IncludeCreate | IncludeUpdate, + IncludeCreateOrUpdate = IncludeCreate | IncludeUpdate + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/TypeConverterExtensions.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/TypeConverterExtensions.cs new file mode 100644 index 00000000000..405a5b5f95c --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/TypeConverterExtensions.cs @@ -0,0 +1,261 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +using System.IO; +using System.Linq; +using System.Xml; +using System.Xml.Serialization; + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.PowerShell +{ + internal static class TypeConverterExtensions + { + internal static T[] SelectToArray(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0]; // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result.ToArray(); + } + + internal static System.Collections.Generic.List SelectToList(object source, System.Func converter) + { + // null begets null + if (source == null) + { + return null; + } + + // single values and strings are just encapsulated in the array. + if (source is string || !(source is System.Collections.IEnumerable)) + { + try + { + return new T[] { (T)converter(source) }.ToList(); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + return new T[0].ToList(); // empty result if couldn't convert. + } + + var result = new System.Collections.Generic.List(); + foreach (var each in (System.Collections.IEnumerable)source) + { + try + { + result.Add((T)converter(each)); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // silent conversion fail + } +#endif + } + return result; + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.Generic.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Collections.IDictionary dictionary) + { + if (null != dictionary) + { + foreach (var each in dictionary.Keys) + { + yield return each; + } + } + } + internal static System.Collections.Generic.IEnumerable GetPropertyKeys(this System.Management.Automation.PSObject instance) + { + if (null != instance) + { + foreach (var each in instance.Properties) + { + yield return each; + } + } + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.Generic.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Collections.IDictionary instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + return (null == instance || instance.Count == 0) ? + Enumerable.Empty>() : + instance.Keys.OfType() + .Where(key => + !(true == exclusions?.Contains(key?.ToString())) + && (false != inclusions?.Contains(key?.ToString()))) + .Select(key => new System.Collections.Generic.KeyValuePair(key, instance[key])); + } + + internal static System.Collections.Generic.IEnumerable> GetFilteredProperties(this System.Management.Automation.PSObject instance, global::System.Collections.Generic.HashSet exclusions = null, global::System.Collections.Generic.HashSet inclusions = null) + { + // new global::System.Collections.Generic.HashSet(System.StringComparer.InvariantCultureIgnoreCase) + return (null == instance || !instance.Properties.Any()) ? + Enumerable.Empty>() : + instance.Properties + .Where(property => + !(true == exclusions?.Contains(property.Name)) + && (false != inclusions?.Contains(property.Name))) + .Select(property => new System.Collections.Generic.KeyValuePair(property.Name, property.Value)); + } + + + internal static T GetValueForProperty(this System.Collections.Generic.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys, each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + internal static T GetValueForProperty(this System.Collections.IDictionary dictionary, string propertyName, T defaultValue, System.Func converter) + { + try + { + var key = System.Linq.Enumerable.FirstOrDefault(dictionary.Keys.OfType(), each => System.String.Equals(each.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return key == null ? defaultValue : (T)converter(dictionary[key]); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static T GetValueForProperty(this System.Management.Automation.PSObject psObject, string propertyName, T defaultValue, System.Func converter) + { + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + return property == null ? defaultValue : (T)converter(property.Value); + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return defaultValue; + } + + internal static bool Contains(this System.Management.Automation.PSObject psObject, string propertyName) + { + bool result = false; + try + { + var property = System.Linq.Enumerable.FirstOrDefault(psObject.Properties, each => System.String.Equals(each.Name.ToString(), propertyName, System.StringComparison.CurrentCultureIgnoreCase)); + result = property == null ? false : true; + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + } +#endif + return result; + } + } +} diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/UndeclaredResponseException.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/UndeclaredResponseException.cs new file mode 100644 index 00000000000..8b750adef23 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/UndeclaredResponseException.cs @@ -0,0 +1,112 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +namespace Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime +{ + using System; + using System.Net.Http; + using System.Net.Http.Headers; + using static Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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.Qumulo.Runtime.Json.JsonNode.Parse(ResponseBody) as Microsoft.Azure.PowerShell.Cmdlets.Qumulo.Runtime.Json.JsonObject; + + // error message could be in properties.statusMessage + { message = If(json?.Property("properties"), out var p) + && If(p?.PropertyT("statusMessage"), out var sm) + ? (string)sm : (string)Message; } + + // see if there is an error block in the body + json = json?.Property("error") ?? json; + + { Code = If(json?.PropertyT("code"), out var c) ? (string)c : (string)StatusCode.ToString(); } + { message = If(json?.PropertyT("message"), out var m) ? (string)m : (string)Message; } + { Action = If(json?.PropertyT("action"), out var a) ? (string)a : (string)Action; } + } +#if DEBUG + catch (System.Exception E) + { + System.Console.Error.WriteLine($"{E.GetType().Name}/{E.Message}/{E.StackTrace}"); + } +#else + catch + { + // couldn't get the code/message from the body response. + // In this case, we will assume the response is the expected error message + if(!string.IsNullOrEmpty(ResponseBody)) { + message = ResponseBody; + } + } +#endif + if (string.IsNullOrEmpty(message)) + { + if (StatusCode >= System.Net.HttpStatusCode.BadRequest && StatusCode < System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Request Error, Status: {StatusCode}"; + } + else if (StatusCode >= System.Net.HttpStatusCode.InternalServerError) + { + message = $"The server responded with a Server Error, Status: {StatusCode}"; + } + else + { + message = $"The server responded with an unrecognized response, Status: {StatusCode}"; + } + } + } + + public void Dispose() + { + ((IDisposable)RequestMessage).Dispose(); + } + } + + public class RestException : RestException + { + public T Error { get; protected set; } + public RestException(System.Net.Http.HttpResponseMessage response, T error) : base(response) + { + Error = error; + } + } + + + public class UndeclaredResponseException : RestException + { + public UndeclaredResponseException(System.Net.Http.HttpResponseMessage response) : base(response) + { + + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Writers/JsonWriter.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/Writers/JsonWriter.cs new file mode 100644 index 00000000000..7330ebbeb86 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/delegates.cs b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/generated/runtime/delegates.cs new file mode 100644 index 00000000000..35f8cd2583d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/how-to.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/how-to.md new file mode 100644 index 00000000000..affbfdd944a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/how-to.md @@ -0,0 +1,58 @@ +# How-To +This document describes how to develop for `Az.Qumulo`. + +## Building `Az.Qumulo` +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.Qumulo` +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.Qumulo` +To pack `Az.Qumulo` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Qumulo`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Qumulo.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Qumulo.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Qumulo`. + - `-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.Qumulo` 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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/Az.Qumulo.internal.psm1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/Az.Qumulo.internal.psm1 new file mode 100644 index 00000000000..ea09aa825af --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/Az.Qumulo.internal.psm1 @@ -0,0 +1,38 @@ +# region Generated + # Load the private module dll + $null = Import-Module -PassThru -Name (Join-Path $PSScriptRoot '..\bin\Az.Qumulo.private.dll') + + # Get the private module's instance + $instance = [Microsoft.Azure.PowerShell.Cmdlets.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/README.md new file mode 100644 index 00000000000..ea6c0ff16a5 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/internal/README.md @@ -0,0 +1,14 @@ +# Internal +This directory contains a module to handle *internal only* cmdlets. Cmdlets that you **hide** in configuration are created here. For more information on hiding, see [cmdlet hiding](https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md#cmdlet-hiding-exportation-suppression). The cmdlets in this directory are generated at **build-time**. Do not put any custom code, files, cmdlets, etc. into this directory. Please use `..\custom` for all custom implementation. + +## Info +- Modifiable: no +- Generated: all +- Committed: no +- Packaged: yes + +## Details +The `Az.Qumulo.internal.psm1` file is generated to this folder. This module file handles the hidden cmdlets. These cmdlets will not be exported by `Az.Qumulo`. Instead, this sub-module is imported by the `..\custom\Az.Qumulo.custom.psm1` module, allowing you to use hidden cmdlets in your custom, exposed cmdlets. To call these cmdlets in your custom scripts, simply use [module-qualified calls](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_command_precedence?view=powershell-6#qualified-names). For example, `Az.Qumulo.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.Qumulo`. diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/license.txt b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/license.txt new file mode 100644 index 00000000000..b9f3180fb9a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/license.txt @@ -0,0 +1,227 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + + +The software includes the AutoMapper library ("AutoMapper"). The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Provided for Informational Purposes Only + +AutoMapper + +The MIT License (MIT) +Copyright (c) 2010 Jimmy Bogard + + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + + + + + +*************** + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/pack-module.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/pack-module.ps1 new file mode 100644 index 00000000000..2f30ca3fffa --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/pack-module.ps1 @@ -0,0 +1,17 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +Write-Host -ForegroundColor Green 'Packing module...' +dotnet pack $PSScriptRoot --no-build /nologo +Write-Host -ForegroundColor Green '-------------Done-------------' \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/resources/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/run-module.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/run-module.ps1 new file mode 100644 index 00000000000..89d60fccd61 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/run-module.ps1 @@ -0,0 +1,62 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Code) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) { + Write-Host -ForegroundColor Green 'Creating isolated process...' + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NoExit -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +$isAzure = $true +if($isAzure) { + . (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts + # Load the latest version of Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) { + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Qumulo.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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test-module.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test-module.ps1 new file mode 100644 index 00000000000..a1cc0c6d11e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test-module.ps1 @@ -0,0 +1,98 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +param([switch]$NotIsolated, [switch]$Live, [switch]$Record, [switch]$Playback, [switch]$RegenerateSupportModule, [switch]$UsePreviousConfigForRecord, [string[]]$TestName) +$ErrorActionPreference = 'Stop' + +if(-not $NotIsolated) +{ + Write-Host -ForegroundColor Green 'Creating isolated process...' + if ($PSBoundParameters.ContainsKey("TestName")) { + $PSBoundParameters["TestName"] = $PSBoundParameters["TestName"] -join "," + } + $pwsh = [System.Diagnostics.Process]::GetCurrentProcess().Path + & "$pwsh" -NonInteractive -NoLogo -NoProfile -File $MyInvocation.MyCommand.Path @PSBoundParameters -NotIsolated + return +} + +# This is a workaround, since for string array parameter, pwsh -File will only take the first element +if ($PSBoundParameters.ContainsKey("TestName") -and ($TestName.count -eq 1) -and ($TestName[0].Contains(','))) { + $TestName = $TestName[0].Split(",") +} + +$ProgressPreference = 'SilentlyContinue' +$baseName = $PSScriptRoot.BaseName +$requireResourceModule = (($baseName -ne "Resources") -and ($Record.IsPresent -or $Live.IsPresent)) +. (Join-Path $PSScriptRoot 'check-dependencies.ps1') -NotIsolated -Accounts:$false -Pester -Resources:$requireResourceModule -RegenerateSupportModule:$RegenerateSupportModule +. ("$PSScriptRoot\test\utils.ps1") + +if ($requireResourceModule) +{ + # Load the latest Az.Accounts installed + Import-Module -Name Az.Accounts -RequiredVersion (Get-Module -Name Az.Accounts -ListAvailable | Sort-Object -Property Version -Descending)[0].Version + $resourceModulePSD = Get-Item -Path (Join-Path $HOME '.PSSharedModules\Resources\Az.Resources.TestSupport.psd1') + Import-Module -Name $resourceModulePSD.FullName +} + +$localModulesPath = Join-Path $PSScriptRoot 'generated\modules' +if(Test-Path -Path $localModulesPath) +{ + $env:PSModulePath = "$localModulesPath$([IO.Path]::PathSeparator)$env:PSModulePath" +} + +$modulePsd1 = Get-Item -Path (Join-Path $PSScriptRoot './Az.Qumulo.psd1') +$modulePath = $modulePsd1.FullName +$moduleName = $modulePsd1.BaseName + +Import-Module -Name Pester +Import-Module -Name $modulePath + +$TestMode = 'playback' +$ExcludeTag = @("LiveOnly") +if($Live) +{ + $TestMode = 'live' + $ExcludeTag = @() +} +if($Record) +{ + $TestMode = 'record' +} +try +{ + if ($TestMode -ne 'playback') + { + setupEnv + } else { + $env:AzPSAutorestTestPlaybackMode = $true + } + $testFolder = Join-Path $PSScriptRoot 'test' + if ($null -ne $TestName) + { + Invoke-Pester -Script @{ Path = $testFolder } -TestName $TestName -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } else { + Invoke-Pester -Script @{ Path = $testFolder } -ExcludeTag $ExcludeTag -EnableExit -OutputFile (Join-Path $testFolder "$moduleName-TestResults.xml") + } +} Finally +{ + if ($TestMode -ne 'playback') + { + cleanupEnv + } + else { + $env:AzPSAutorestTestPlaybackMode = '' + } +} + +Write-Host -ForegroundColor Green '-------------Done-------------' diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test/loadEnv.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test/loadEnv.ps1 new file mode 100644 index 00000000000..6a7c385c6b7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/test/loadEnv.ps1 @@ -0,0 +1,29 @@ +# ---------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# Code generated by Microsoft (R) AutoRest Code Generator.Changes may cause incorrect behavior and will be lost if the code +# is regenerated. +# ---------------------------------------------------------------------------------- +$envFile = 'env.json' +if ($TestMode -eq 'live') { + $envFile = 'localEnv.json' +} + +if (Test-Path -Path (Join-Path $PSScriptRoot $envFile)) { + $envFilePath = Join-Path $PSScriptRoot $envFile +} else { + $envFilePath = Join-Path $PSScriptRoot '..\$envFile' +} +$env = @{} +if (Test-Path -Path $envFilePath) { + $env = Get-Content (Join-Path $PSScriptRoot $envFile) | ConvertFrom-Json + $PSDefaultParameterValues=@{"*:Tenant"=$env.Tenant} +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/.gitattributes b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/.gitattributes new file mode 100644 index 00000000000..2125666142e --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/.gitattributes @@ -0,0 +1 @@ +* text=auto \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/README.md new file mode 100644 index 00000000000..cdaf3a995a7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/README.md @@ -0,0 +1,438 @@ + +# Az.Resources.TestSupport +This directory contains the PowerShell module for the Resources service. + +--- +## Info +- Modifiable: yes +- Generated: all +- Committed: yes +- Packaged: yes + +--- +## Detail +This module was primarily generated via [AutoRest](https://github.com/Azure/autorest) using the [PowerShell](https://github.com/Azure/autorest.powershell) extension. + +## Module Requirements +- [Az.Accounts module](https://www.powershellgallery.com/packages/Az.Accounts/), version 2.7.5 or greater + +## Authentication +AutoRest does not generate authentication code for the module. Authentication is handled via Az.Accounts by altering the HTTP payload before it is sent. + +## Development +For information on how to develop for `Az.Resources.TestSupport`, 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
`npm install -g 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` + +--- +### AutoRest Configuration +> see https://aka.ms/autorest + +> Values +``` yaml +azure: true +powershell: true +branch: master +repo: https://github.com/Azure/azure-rest-api-specs/blob/$(branch) +metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + copyright: Microsoft Corporation. All rights reserved. + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell +``` + +> Names +``` yaml +prefix: Az +``` + +> Folders +``` yaml +clear-output-folder: true +``` + +``` yaml +input-file: + - $(repo)/specification/resources/resource-manager/Microsoft.Resources/stable/2018-05-01/resources.json +module-name: Az.Resources.TestSupport +namespace: Microsoft.Azure.PowerShell.Cmdlets.Resources + +subject-prefix: '' +module-version: 0.0.1 +title: Resources + +directive: + - remove-operation: Deployments_CreateOrUpdateAtSubscriptionScope + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - from: swagger-document + where: $..parameters[?(@.name=='$filter')] + transform: $['x-ms-skip-url-encoding'] = true + - from: swagger-document + where: $..[?( /Resources_(CreateOrUpdate|Update|Delete|Get|GetById|CheckExistence|CheckExistenceById)/g.exec(@.operationId))] + transform: "$.parameters = $.parameters.map( each => { each.name = each.name === 'api-version' ? 'explicit-api-version' : each.name; return each; } );" + - from: source-file-csharp + where: $ + transform: $ = $.replace(/explicit-api-version/g, 'api-version'); + - where: + parameter-name: ExplicitApiVersion + set: + parameter-name: ApiVersion + - from: source-file-csharp + where: $ + transform: > + $ = $.replace(/result.OdataNextLink/g,'nextLink' ); + return $.replace( /(^\s*)(if\s*\(\s*nextLink\s*!=\s*null\s*\))/gm, '$1var nextLink = Module.Instance.FixNextLink(responseMessage, result.OdataNextLink);\n$1$2' ); + - from: swagger-document + where: + - $..DeploymentProperties.properties.template + - $..DeploymentProperties.properties.parameters + - $..ResourceGroupExportResult.properties.template + - $..PolicyDefinitionProperties.properties.policyRule + transform: $.additionalProperties = true; + - where: + verb: Set + subject: Resource + remove: true + - where: + verb: Set + subject: Deployment + remove: true + - where: + subject: Resource + parameter-name: GroupName + set: + parameter-name: ResourceGroupName + clear-alias: true + - where: + subject: Resource + parameter-name: Id + set: + parameter-name: ResourceId + clear-alias: true + - where: + subject: Resource + parameter-name: Type + set: + parameter-name: ResourceType + clear-alias: true + - where: + subject: Appliance* + remove: true + - where: + verb: Test + subject: CheckNameAvailability + set: + subject: NameAvailability + - where: + verb: Export + subject: ResourceGroupTemplate + set: + subject: ResourceGroup + alias: Export-AzResourceGroupTemplate + - where: + parameter-name: Filter + set: + alias: ODataQuery + - where: + verb: Test + subject: ResourceGroupExistence + set: + subject: ResourceGroup + alias: Test-AzResourceGroupExistence + - where: + verb: Export + subject: DeploymentTemplate + set: + alias: [Save-AzDeploymentTemplate, Save-AzResourceGroupDeploymentTemplate] + - where: + subject: Deployment + set: + alias: ${verb}-AzResourceGroupDeployment + - where: + verb: Get + subject: DeploymentOperation + set: + alias: Get-AzResourceGroupDeploymentOperation + - where: + verb: New + subject: Deployment + variant: Create.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + hide: true + - where: + verb: Test + subject: Deployment + variant: Validate.*Expanded.* + parameter-name: Parameter + set: + parameter-name: DeploymentPropertyParameter + - where: + verb: New + subject: Deployment + parameter-name: DebugSettingDetailLevel + set: + parameter-name: DeploymentDebugLogLevel + - where: + subject: Provider + set: + subject: ResourceProvider + - where: + subject: ProviderFeature|ResourceProvider|ResourceLock + parameter-name: ResourceProviderNamespace + set: + alias: ProviderNamespace + - where: + verb: Update + subject: ResourceGroup + parameter-name: Name + clear-alias: true + - where: + parameter-name: UpnOrObjectId + set: + alias: ['UserPrincipalName', 'Upn', 'ObjectId'] + - where: + subject: Deployment + variant: (.*)Expanded(.*) + parameter-name: Parameter + set: + parameter-name: DeploymentParameter + # Format output + - where: + model-name: GenericResource + set: + format-table: + properties: + - Name + - ResourceGroupName + - Type + - Location + labels: + Type: ResourceType + - where: + model-name: ResourceGroup + set: + format-table: + properties: + - Name + - Location + - ProvisioningState + - where: + model-name: DeploymentExtended + set: + format-table: + properties: + - Name + - ProvisioningState + - Timestamp + - Mode + - where: + model-name: PolicyAssignment + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicyDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: PolicySetDefinition + set: + format-table: + properties: + - Name + - DisplayName + - Id + - where: + model-name: Provider + set: + format-table: + properties: + - Namespace + - RegistrationState + - where: + model-name: ProviderResourceType + set: + format-table: + properties: + - ResourceType + - Location + - ApiVersion + - where: + model-name: FeatureResult + set: + format-table: + properties: + - Name + - State + - where: + model-name: TagDetails + set: + format-table: + properties: + - TagName + - CountValue + - where: + model-name: Application + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppId + - Homepage + - AvailableToOtherTenant + - where: + model-name: KeyCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - Type + - where: + model-name: PasswordCredential + set: + format-table: + properties: + - StartDate + - EndDate + - KeyId + - where: + model-name: User + set: + format-table: + properties: + - PrincipalName + - DisplayName + - ObjectId + - Type + - where: + model-name: AdGroup + set: + format-table: + properties: + - DisplayName + - Mail + - ObjectId + - SecurityEnabled + - where: + model-name: ServicePrincipal + set: + format-table: + properties: + - DisplayName + - ObjectId + - AppDisplayName + - AppId + - where: + model-name: Location + set: + format-table: + properties: + - Name + - DisplayName + - where: + model-name: ManagementLockObject + set: + format-table: + properties: + - Name + - Level + - ResourceId + - where: + model-name: RoleAssignment + set: + format-table: + properties: + - DisplayName + - ObjectId + - ObjectType + - RoleDefinitionName + - Scope + - where: + model-name: RoleDefinition + set: + format-table: + properties: + - RoleName + - Name + - Action +# To remove cmdlets not used in the test frame + - where: + subject: Operation + remove: true + - where: + subject: Deployment + variant: (.*)1|Cancel(.*)|Validate(.*)|Export(.*)|List(.*)|Delete(.*)|Check(.*)|Calculate(.*) + remove: true + - where: + subject: ResourceProvider + variant: Register(.*)|Unregister(.*)|Get(.*) + remove: true + - where: + subject: ResourceGroup + variant: List(.*)|Update(.*)|Export(.*)|Move(.*) + remove: true + - where: + subject: Resource + remove: true + - where: + subject: Tag|TagValue + remove: true + - where: + subject: DeploymentOperation + remove: true + - where: + subject: DeploymentTemplate + remove: true + - where: + subject: Calculate(.*) + remove: true + - where: + subject: ResourceExistence + remove: true + - where: + subject: ResourceMoveResource + remove: true + - where: + subject: DeploymentExistence + remove: true +``` diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/custom/New-AzDeployment.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/custom/New-AzDeployment.ps1 new file mode 100644 index 00000000000..84228dd80a1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/custom/New-AzDeployment.ps1 @@ -0,0 +1,231 @@ +function New-AzDeployment { + [OutputType('Microsoft.Azure.PowerShell.Cmdlets.Resources.Models.IDeploymentExtended')] + [CmdletBinding(DefaultParameterSetName='CreateWithTemplateFileParameterFile', PositionalBinding=$false, SupportsShouldProcess, ConfirmImpact='Medium')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Description('You can provide the template and parameters directly in the request or link to JSON files.')] + param( + [Parameter(HelpMessage='The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name.')] + [Alias('DeploymentName')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='deploymentName', Required, PossibleTypes=([System.String]), Description='The name of the deployment.')] + [System.String] + # The name of the deployment. If not provided, the name of the template file will be used. If a template file is not used, a random GUID will be used for the name. + ${Name}, + + [Parameter(Mandatory, HelpMessage='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='subscriptionId', Required, PossibleTypes=([System.String]), Description='The ID of the target subscription.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.DefaultInfo(Script='(Get-AzContext).Subscription.Id')] + [System.String] + # The ID of the target subscription. + ${SubscriptionId}, + + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Path')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='resourceGroupName', Required, PossibleTypes=([System.String]), Description='The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist.')] + [System.String] + # The name of the resource group to deploy the resources to. The name is case insensitive. The resource group must already exist. + ${ResourceGroupName}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='Local path to the JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='Local path to the JSON template file.')] + [System.String] + # Local path to the JSON template file. + ${TemplateFile}, + + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The string representation of the JSON template.')] + [System.String] + # The string representation of the JSON template. + ${TemplateJson}, + + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the JSON template. + ${TemplateObject}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterFile', Mandatory, HelpMessage='Local path to the parameter JSON template file.')] + [System.String] + # Local path to the parameter JSON template file. + ${TemplateParameterFile}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterJson', Mandatory, HelpMessage='The string representation of the parameter JSON template.')] + [System.String] + # The string representation of the parameter JSON template. + ${TemplateParameterJson}, + + [Parameter(ParameterSetName='CreateWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateFileParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateJsonParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [Parameter(ParameterSetName='CreateRGWithTemplateObjectParameterObject', Mandatory, HelpMessage='The hashtable representation of the parameter JSON template.')] + [System.Collections.Hashtable] + # The hashtable representation of the parameter JSON template. + ${TemplateParameterObject}, + + [Parameter(Mandatory, HelpMessage='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [ArgumentCompleter([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode])] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='mode', Required, PossibleTypes=([Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode]), Description='The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Support.DeploymentMode] + # The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. + ${Mode}, + + [Parameter(HelpMessage='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='detailLevel', PossibleTypes=([System.String]), Description='Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.')] + [System.String] + # Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations. + ${DeploymentDebugLogLevel}, + + [Parameter(HelpMessage='The location to store the deployment data.')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Body')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Runtime.Info(SerializedName='location', PossibleTypes=([System.String]), Description='The location to store the deployment data.')] + [System.String] + # The location to store the deployment data. + ${Location}, + + [Parameter(HelpMessage='The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription.')] + [Alias('AzureRMContext', 'AzureCredential')] + [ValidateNotNull()] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Azure')] + [System.Management.Automation.PSObject] + # The DefaultProfile parameter is not functional. Use the SubscriptionId parameter when available if executing the cmdlet against a different subscription. + ${DefaultProfile}, + + [Parameter(HelpMessage='Run the command as a job')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command as a job + ${AsJob}, + + [Parameter(HelpMessage='Run the command asynchronously')] + [Microsoft.Azure.PowerShell.Cmdlets.Resources.Category('Runtime')] + [System.Management.Automation.SwitchParameter] + # Run the command asynchronously + ${NoWait} + + ) + + process { + if ($PSBoundParameters.ContainsKey("TemplateFile")) + { + if (!(Test-Path -Path $TemplateFile)) + { + throw "Unable to find template file '$TemplateFile'." + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (Get-Item -Path $TemplateFile).BaseName + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + $TemplateJson = [System.IO.File]::ReadAllText($TemplateFile) + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateJson")) + { + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateObject")) + { + $TemplateJson = ConvertTo-Json -InputObject $TemplateObject + $null = $PSBoundParameters.Add("Template", $TemplateJson) + $null = $PSBoundParameters.Remove("TemplateObject") + } + + if ($PSBoundParameters.ContainsKey("TemplateParameterFile")) + { + if (!(Test-Path -Path $TemplateParameterFile)) + { + throw "Unable to find template parameter file '$TemplateParameterFile'." + } + + $ParameterJson = [System.IO.File]::ReadAllText($TemplateParameterFile) + $ParameterObject = ConvertFrom-Json -InputObject $ParameterJson + $ParameterHashtable = @{} + $ParameterObject.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + $ParameterHashtable.Remove("`$schema") + $ParameterHashtable.Remove("contentVersion") + $NestedValues = $ParameterHashtable.parameters + if ($null -ne $NestedValues) + { + $ParameterHashtable.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $ParameterHashtable[$_.Name] = $_.Value } + } + + $ParameterJson = ConvertTo-Json -InputObject $ParameterHashtable + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $ParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterFile") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterJson")) + { + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterJson") + } + elseif ($PSBoundParameters.ContainsKey("TemplateParameterObject")) + { + $TemplateParameterObject.Remove("`$schema") + $TemplateParameterObject.Remove("contentVersion") + $NestedValues = $TemplateParameterObject.parameters + if ($null -ne $NestedValues) + { + $TemplateParameterObject.Remove("parameters") + $NestedValues.PSObject.Properties | ForEach-Object { $TemplateParameterObject[$_.Name] = $_.Value } + } + + $TemplateParameterJson = ConvertTo-Json -InputObject $TemplateParameterObject + $null = $PSBoundParameters.Add("DeploymentPropertyParameter", $TemplateParameterJson) + $null = $PSBoundParameters.Remove("TemplateParameterObject") + } + + if (!$PSBoundParameters.ContainsKey("Name")) + { + $DeploymentName = (New-Guid).Guid + $null = $PSBoundParameters.Add("Name", $DeploymentName) + } + + if ($PSBoundParameters.ContainsKey("ResourceGroupName")) + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + else + { + Az.Resources.TestSupport.private\New-AzDeployment_CreateExpanded @PSBoundParameters + } + } +} \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/docs/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/docs/README.md new file mode 100644 index 00000000000..3b56cb561c1 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/docs/README.md @@ -0,0 +1,11 @@ +# Docs +This directory contains the documentation of the cmdlets for the `Az.Resources` module. To run documentation generation, use the `generate-help.ps1` script at the root module folder. Files in this folder will *always be overriden on regeneration*. To update documentation examples, please use the `..\examples` folder. + +## Info +- Modifiable: no +- Generated: all +- Committed: yes +- Packaged: yes + +## Details +The process of documentation generation loads `Az.Resources` and analyzes the exported cmdlets from the module. It recognizes the [help comments](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_comment_based_help) that are generated into the scripts in the `..\exports` folder. Additionally, when writing custom cmdlets in the `..\custom` folder, you can use the help comments syntax, which decorate the exported scripts at build-time. The documentation examples are taken from the `..\examples` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/examples/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/examples/README.md new file mode 100644 index 00000000000..ac871d71fc7 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/examples/README.md @@ -0,0 +1,11 @@ +# Examples +This directory contains examples from the exported cmdlets of the module. When `build-module.ps1` is ran, example stub files will be generated here. If your module support Azure Profiles, the example stubs will be in individual profile folders. These example stubs should be updated to show how the cmdlet is used. The examples are imported into the documentation when `generate-help.ps1` is ran. + +## Info +- Modifiable: yes +- Generated: partial +- Committed: yes +- Packaged: no + +## Purpose +This separates the example documentation details from the generated documentation information provided directly from the generated cmdlets. Since the cmdlets don't have examples from the REST spec, this provides a means to add examples easily. The example stubs provide the markdown format that is required. The 3 core elements are: the name of the example, the code information of the example, and the description of the example. That information, if the markdown format is followed, will be available to documentation generation and be part of the documents in the `..\docs` folder. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/how-to.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/how-to.md new file mode 100644 index 00000000000..129cad12cc3 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/how-to.md @@ -0,0 +1,60 @@ +# How-To +This document describes how to develop for `Az.Resources`. + +## Building `Az.Resources` +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.Resources` +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.Resources` +To pack `Az.Resources` for distribution, run the `pack-module.ps1` script. This will take the contents of multiple directories and certain root-folder files to create a `.nupkg`. The structure of the `.nupkg` is created so it can be loaded part of a [PSRepository](https://learn.microsoft.com/powershell/module/powershellget/register-psrepository). Additionally, this package is in a format for distribution to the [PSGallery](https://www.powershellgallery.com/). For signing an Azure module, please contact the [Azure PowerShell](https://github.com/Azure/azure-powershell) team. + +## Module Script Details +There are multiple scripts created for performing different actions for developing `Az.Resources`. +- `build-module.ps1` + - Builds the module DLL (`./bin/Az.Resources.private.dll`), creates the exported cmdlets and documentation, generates custom cmdlet test stubs and exported cmdlet example stubs, and updates `./Az.Resources.psd1` with Azure profile information. + - **Parameters**: [`Switch` parameters] + - `-Run`: After building, creates an isolated PowerShell session and loads `Az.Resources`. + - `-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.Resources` 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`. +- `generate-portal-ux.ps1` + - Generates a folder dedicated to Azure-specific content and includes metadata files essential for enhancing the user experience (UX) within the Azure portal. +- `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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/license.txt b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/license.txt new file mode 100644 index 00000000000..3d3f8f90d5d --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/license.txt @@ -0,0 +1,203 @@ +MICROSOFT SOFTWARE LICENSE TERMS + +MICROSOFT AZURE POWERSHELL + +These license terms are an agreement between Microsoft Corporation (or based on where you live, one of its affiliates) and you. Please read them. They apply to the software named above, which includes the media on which you received it, if any. + +BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT THEM, DO NOT USE THE SOFTWARE. + + +-----------------START OF LICENSE-------------------------- + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +-------------------END OF LICENSE------------------------------------------ + + +----------------START OF THIRD PARTY NOTICE-------------------------------- + +The software includes Newtonsoft.Json. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software. + +Newtonsoft.Json + +The MIT License (MIT) +Copyright (c) 2007 James Newton-King +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +-------------END OF THIRD PARTY NOTICE---------------------------------------- + diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md new file mode 100644 index 00000000000..278ea694e0f --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/CmdletSurface-latest-2019-04-30.md @@ -0,0 +1,598 @@ +### AzADApplication [Get, New, Remove, Update] `IApplication, Boolean` + - TenantId `String` + - ObjectId `String` + - IncludeDeleted `SwitchParameter` + - InputObject `IResourcesIdentity` + - HardDelete `SwitchParameter` + - Filter `String` + - IdentifierUri `String` + - DisplayNameStartWith `String` + - DisplayName `String` + - ApplicationId `String` + - AllowGuestsSignIn `SwitchParameter` + - AllowPassthroughUser `SwitchParameter` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenants `SwitchParameter` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes` + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `SwitchParameter` + - Oauth2AllowUrlPathMatching `SwitchParameter` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `SwitchParameter` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `SwitchParameter` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + - Parameter `IApplicationCreateParameters` + - PassThru `SwitchParameter` + - AvailableToOtherTenant `SwitchParameter` + +### AzADApplicationOwner [Add, Get, Remove] `Boolean, IDirectoryObject` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADDeletedApplication [Restore] `IApplication` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + +### AzADGroup [Get, New, Remove] `IAdGroup, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayNameStartsWith `String` + - DisplayName `String` + - AdditionalProperties `Hashtable` + - MailNickname `String` + - Parameter `IGroupCreateParameters` + - PassThru `SwitchParameter` + +### AzADGroupMember [Add, Get, Remove, Test] `Boolean, IDirectoryObject, SwitchParameter` + - GroupObjectId `String` + - TenantId `String` + - MemberObjectId `String[]` + - MemberUserPrincipalName `String[]` + - GroupObject `IAdGroup` + - GroupDisplayName `String` + - InputObject `IResourcesIdentity` + - ObjectId `String` + - ShowOwner `SwitchParameter` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IGroupAddMemberParameters` + - DisplayName `String` + - GroupId `String` + - MemberId `String` + +### AzADGroupMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IGroupGetMemberGroupsParameters` + +### AzADGroupOwner [Add, Remove] `Boolean` + - ObjectId `String` + - TenantId `String` + - GroupObjectId `String` + - MemberObjectId `String[]` + - InputObject `IResourcesIdentity` + - OwnerObjectId `String` + - PassThru `SwitchParameter` + - AdditionalProperties `Hashtable` + - Url `String` + - Parameter `IAddOwnerParameters` + +### AzADObject [Get] `IDirectoryObject` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - IncludeDirectoryObjectReference `SwitchParameter` + - ObjectId `String[]` + - Type `String[]` + - Parameter `IGetObjectsParameters` + +### AzADServicePrincipal [Get, New, Remove, Update] `IServicePrincipal, Boolean` + - TenantId `String` + - ObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ApplicationObject `IApplication` + - ServicePrincipalName `String` + - DisplayNameBeginsWith `String` + - DisplayName `String` + - ApplicationId `String` + - AccountEnabled `SwitchParameter` + - AppId `String` + - AppRoleAssignmentRequired `SwitchParameter` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + - Parameter `IServicePrincipalCreateParameters` + - PassThru `SwitchParameter` + +### AzADServicePrincipalOwner [Get] `IDirectoryObject` + - ObjectId `String` + - TenantId `String` + +### AzADUser [Get, New, Remove, Update] `IUser, Boolean` + - TenantId `String` + - UpnOrObjectId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - DisplayName `String` + - StartsWith `String` + - Mail `String` + - MailNickname `String` + - Parameter `IUserCreateParameters` + - AccountEnabled `SwitchParameter` + - GivenName `String` + - ImmutableId `String` + - PasswordProfile `IPasswordProfile` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType` + - PassThru `SwitchParameter` + - EnableAccount `SwitchParameter` + +### AzADUserMemberGroup [Get] `String` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - AdditionalProperties `Hashtable` + - SecurityEnabledOnly `SwitchParameter` + - Parameter `IUserGetMemberGroupsParameters` + +### AzApplicationKeyCredentials [Get, Update] `IKeyCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IKeyCredentialsUpdateParameters` + - Value `IKeyCredential[]` + +### AzApplicationPasswordCredentials [Get, Update] `IPasswordCredential, Boolean` + - ObjectId `String` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Parameter `IPasswordCredentialsUpdateParameters` + - Value `IPasswordCredential[]` + +### AzAuthorizationOperation [Get] `IOperation` + +### AzClassicAdministrator [Get] `IClassicAdministrator` + - SubscriptionId `String[]` + +### AzDenyAssignment [Get] `IDenyAssignment` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - Filter `String` + +### AzDeployment [Get, New, Remove, Set, Stop, Test] `IDeploymentExtended, Boolean, IDeploymentValidateResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Top `Int32` + - Parameter `IDeployment` + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - PassThru `SwitchParameter` + +### AzDeploymentExistence [Test] `Boolean` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDeploymentOperation [Get] `IDeploymentOperation` + - DeploymentName `String` + - SubscriptionId `String[]` + - ResourceGroupName `String` + - OperationId `String` + - DeploymentObject `IDeploymentExtended` + - InputObject `IResourcesIdentity` + - Top `Int32` + +### AzDeploymentTemplate [Export] `IDeploymentExportResultTemplate` + - DeploymentName `String` + - SubscriptionId `String` + - ResourceGroupName `String` + - InputObject `IResourcesIdentity` + +### AzDomain [Get] `IDomain` + - TenantId `String` + - Name `String` + - InputObject `IResourcesIdentity` + - Filter `String` + +### AzElevateGlobalAdministratorAccess [Invoke] `Boolean` + +### AzEntity [Get] `IEntityInfo` + - Filter `String` + - GroupName `String` + - Search `String` + - Select `String` + - Skip `Int32` + - Skiptoken `String` + - Top `Int32` + - View `String` + - CacheControl `String` + +### AzManagedApplication [Get, New, Remove, Set, Update] `IApplication, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplication` + - ApplicationDefinitionId `String` + - IdentityType `ResourceIdentityType` + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagedApplicationDefinition [Get, New, Remove, Set] `IApplicationDefinition, Boolean` + - Id `String` + - Name `String` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - Parameter `IApplicationDefinition` + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - PackageFileUri `String` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `Hashtable` + +### AzManagementGroup [Get, New, Remove, Set, Update] `IManagementGroup, IManagementGroupInfo, Boolean` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Expand `String` + - Filter `String` + - Recurse `SwitchParameter` + - CacheControl `String` + - DisplayName `String` + - Name `String` + - ParentId `String` + - CreateManagementGroupRequest `ICreateManagementGroupRequest` + - PatchGroupRequest `IPatchManagementGroupRequest` + +### AzManagementGroupDescendant [Get] `IDescendantInfo` + - GroupId `String` + - InputObject `IResourcesIdentity` + - Skiptoken `String` + - Top `Int32` + +### AzManagementGroupSubscription [New, Remove] `Boolean` + - GroupId `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - CacheControl `String` + +### AzManagementLock [Get, New, Remove, Set] `IManagementLockObject, Boolean` + - SubscriptionId `String[]` + - LockName `String` + - ResourceGroupName `String` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - Level `LockLevel` + - Note `String` + - Owner `IManagementLockOwner[]` + - Parameter `IManagementLockObject` + +### AzNameAvailability [Test] `ICheckNameAvailabilityResult` + - Name `String` + - Type `Type` + - CheckNameAvailabilityRequest `ICheckNameAvailabilityRequest` + +### AzOAuth2PermissionGrant [Get, New, Remove] `IOAuth2PermissionGrant, Boolean` + - TenantId `String` + - InputObject `IResourcesIdentity` + - Filter `String` + - ClientId `String` + - ConsentType `ConsentType` + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + - Body `IOAuth2PermissionGrant` + +### AzPermission [Get] `IPermission` + - ResourceGroupName `String` + - SubscriptionId `String[]` + - ParentResourcePath `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + +### AzPolicyAssignment [Get, New, Remove] `IPolicyAssignment` + - Id `String` + - Name `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - ParentResourcePath `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - PolicyDefinitionId `String` + - IncludeDescendent `SwitchParameter` + - Filter `String` + - Parameter `IPolicyAssignment` + - Description `String` + - DisplayName `String` + - IdentityType `ResourceIdentityType` + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - SkuName `String` + - SkuTier `String` + - PropertiesScope `String` + +### AzPolicyDefinition [Get, New, Remove, Set] `IPolicyDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicyDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzPolicySetDefinition [Get, New, Remove, Set] `IPolicySetDefinition, Boolean` + - SubscriptionId `String[]` + - Name `String` + - ManagementGroupName `String` + - Id `String` + - InputObject `IResourcesIdentity` + - BuiltIn `SwitchParameter` + - Parameter `IPolicySetDefinition` + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType` + - PassThru `SwitchParameter` + +### AzProviderFeature [Get, Register] `IFeatureResult` + - SubscriptionId `String[]` + - Name `String` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + +### AzProviderOperationsMetadata [Get] `IProviderOperationsMetadata` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + +### AzResource [Get, Move, New, Remove, Set, Test, Update] `IGenericResource, Boolean` + - ResourceId `String` + - Name `String` + - ParentResourcePath `String` + - ProviderNamespace `String` + - ResourceGroupName `String` + - ResourceType `String` + - SubscriptionId `String[]` + - InputObject `IResourcesIdentity` + - SourceResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - Expand `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Filter `String` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + - IdentityType `ResourceIdentityType` + - IdentityUserAssignedIdentity `Hashtable` + - Kind `String` + - Location `String` + - ManagedBy `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + +### AzResourceGroup [Export, Get, New, Remove, Set, Test, Update] `IResourceGroupExportResult, IResourceGroup, Boolean` + - ResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Id `String` + - Filter `String` + - Top `Int32` + - TagName `String` + - TagValue `String` + - Tag `Hashtable` + - Option `String` + - Resource `String[]` + - Parameter `IExportTemplateRequest` + - Location `String` + - ManagedBy `String` + +### AzResourceLink [Get, New, Remove, Set] `IResourceLink, Boolean` + - ResourceId `String` + - InputObject `IResourcesIdentity` + - SubscriptionId `String[]` + - Scope `String` + - FilterById `String` + - FilterByScope `Filter` + - Note `String` + - TargetId `String` + - Parameter `IResourceLink` + +### AzResourceMove [Test] `Boolean` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + - Resource `String[]` + - TargetResourceGroup `String` + - TargetSubscriptionId `String` + - TargetResourceGroupName `String` + - Parameter `IResourcesMoveInfo` + +### AzResourceProvider [Get, Register, Unregister] `IProvider` + - SubscriptionId `String[]` + - ResourceProviderNamespace `String` + - InputObject `IResourcesIdentity` + - Expand `String` + - Top `Int32` + +### AzResourceProviderOperationDetail [Get] `IResourceProviderOperationDefinition` + - ResourceProviderNamespace `String` + +### AzRoleAssignment [Get, New, Remove] `IRoleAssignment` + - Id `String` + - Name `String` + - Scope `String` + - RoleId `String` + - InputObject `IResourcesIdentity` + - ParentResourceId `String` + - ResourceGroupName `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - SubscriptionId `String[]` + - ExpandPrincipalGroups `String` + - ServicePrincipalName `String` + - SignInName `String` + - Filter `String` + - CanDelegate `SwitchParameter` + - PrincipalId `String` + - RoleDefinitionId `String` + - Parameter `IRoleAssignmentCreateParameters` + - PrincipalType `PrincipalType` + +### AzRoleDefinition [Get, New, Remove, Set] `IRoleDefinition` + - Id `String` + - Scope `String` + - InputObject `IResourcesIdentity` + - Name `String` + - Custom `SwitchParameter` + - Filter `String` + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - RoleDefinition `IRoleDefinition` + +### AzSubscriptionLocation [Get] `ILocation` + - SubscriptionId `String[]` + +### AzTag [Get, New, Remove] `ITagDetails, Boolean` + - SubscriptionId `String[]` + - Name `String` + - Value `String` + - InputObject `IResourcesIdentity` + - PassThru `SwitchParameter` + +### AzTenantBackfill [Start] `ITenantBackfillStatusResult` + +### AzTenantBackfillStatus [Invoke] `ITenantBackfillStatusResult` + diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/ModelSurface.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/ModelSurface.md new file mode 100644 index 00000000000..378e3ec418a --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/ModelSurface.md @@ -0,0 +1,1645 @@ +### AddOwnerParameters \ [Api16] + - Url `String` + +### AdGroup \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - Mail `String` + - MailEnabled `Boolean?` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - SecurityEnabled `Boolean?` + +### AliasPathType [Api20180501] + - ApiVersion `String[]` + - Path `String` + +### AliasType [Api20180501] + - Name `String` + - Path `IAliasPathType[]` + +### Appliance [Api20160901Preview] + - DefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceArtifact [Api20160901Preview] + - Name `String` + - Type `ApplianceArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplianceDefinition [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplianceDefinitionListResult [Api20160901Preview] + - NextLink `String` + - Value `IApplianceDefinition[]` + +### ApplianceDefinitionProperties [Api20160901Preview] + - Artifact `IApplianceArtifact[]` + - Authorization `IApplianceProviderAuthorization[]` + - Description `String` + - DisplayName `String` + - LockLevel `ApplianceLockLevel` **{CanNotDelete, None, ReadOnly}** + - PackageFileUri `String` + +### ApplianceListResult [Api20160901Preview] + - NextLink `String` + - Value `IAppliance[]` + +### AppliancePatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplianceProperties [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesOutputs` + - Parameter `IAppliancePropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### AppliancePropertiesPatchable [Api20160901Preview] + - ApplianceDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IAppliancePropertiesPatchableOutputs` + - Parameter `IAppliancePropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplianceProviderAuthorization [Api20160901Preview] + - PrincipalId `String` + - RoleDefinitionId `String` + +### Application \ [Api16, Api20170901, Api20180601] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppId `String` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DefinitionId `String` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - Id `String` + - IdentifierUri `String[]` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - Kind `String` + - KnownClientApplication `String[]` + - Location `String` + - LogoutUrl `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - ObjectId `String` + - ObjectType `String` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - PasswordCredentials `IPasswordCredential[]` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - ProvisioningState `String` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + - WwwHomepage `String` + +### ApplicationArtifact [Api20170901] + - Name `String` + - Type `ApplicationArtifactType?` **{Custom, Template}** + - Uri `String` + +### ApplicationBase [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationCreateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### ApplicationDefinition [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IsEnabled `String` + - Location `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - ManagedBy `String` + - Name `String` + - PackageFileUri `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### ApplicationDefinitionListResult [Api20180601] + - NextLink `String` + - Value `IApplicationDefinition[]` + +### ApplicationDefinitionProperties [Api20170901] + - Artifact `IApplicationArtifact[]` + - Authorization `IApplicationProviderAuthorization[]` + - CreateUiDefinition `IApplicationDefinitionPropertiesCreateUiDefinition` + - Description `String` + - DisplayName `String` + - IsEnabled `String` + - LockLevel `ApplicationLockLevel` **{CanNotDelete, None, ReadOnly}** + - MainTemplate `IApplicationDefinitionPropertiesMainTemplate` + - PackageFileUri `String` + +### ApplicationListResult [Api16, Api20180601] + - NextLink `String` + - OdataNextLink `String` + - Value `IApplication[]` + +### ApplicationPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - Id `String` + - Identity `IIdentity` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Kind `String` + - Location `String` + - ManagedBy `String` + - ManagedResourceGroupId `String` + - Name `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - ProvisioningState `String` + - Sku `ISku` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + - UiDefinitionUri `String` + +### ApplicationProperties [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesOutputs` + - Parameter `IApplicationPropertiesParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationPropertiesPatchable [Api20170901, Api20180601] + - ApplicationDefinitionId `String` + - ManagedResourceGroupId `String` + - Output `IApplicationPropertiesPatchableOutputs` + - Parameter `IApplicationPropertiesPatchableParameters` + - ProvisioningState `String` + - UiDefinitionUri `String` + +### ApplicationProviderAuthorization [Api20170901] + - PrincipalId `String` + - RoleDefinitionId `String` + +### ApplicationUpdateParameters [Api16] + - AllowGuestsSignIn `Boolean?` + - AllowPassthroughUser `Boolean?` + - AppLogoUrl `String` + - AppPermission `String[]` + - AppRole `IAppRole[]` + - AvailableToOtherTenant `Boolean?` + - DisplayName `String` + - ErrorUrl `String` + - GroupMembershipClaim `GroupMembershipClaimTypes?` **{All, None, SecurityGroup}** + - Homepage `String` + - IdentifierUri `String[]` + - InformationalUrl `IInformationalUrl` + - InformationalUrlMarketing `String` + - InformationalUrlPrivacy `String` + - InformationalUrlSupport `String` + - InformationalUrlTermsOfService `String` + - IsDeviceOnlyAuthSupported `Boolean?` + - KeyCredentials `IKeyCredential[]` + - KnownClientApplication `String[]` + - LogoutUrl `String` + - Oauth2AllowImplicitFlow `Boolean?` + - Oauth2AllowUrlPathMatching `Boolean?` + - Oauth2Permission `IOAuth2Permission[]` + - Oauth2RequirePostResponse `Boolean?` + - OptionalClaim `IOptionalClaims` + - OptionalClaimAccessToken `IOptionalClaim[]` + - OptionalClaimIdToken `IOptionalClaim[]` + - OptionalClaimSamlToken `IOptionalClaim[]` + - OrgRestriction `String[]` + - PasswordCredentials `IPasswordCredential[]` + - PreAuthorizedApplication `IPreAuthorizedApplication[]` + - PublicClient `Boolean?` + - PublisherDomain `String` + - ReplyUrl `String[]` + - RequiredResourceAccess `IRequiredResourceAccess[]` + - SamlMetadataUrl `String` + - SignInAudience `String` + - WwwHomepage `String` + +### AppRole [Api16] + - AllowedMemberType `String[]` + - Description `String` + - DisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Value `String` + +### BasicDependency [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### CheckGroupMembershipParameters \ [Api16] + - GroupId `String` + - MemberId `String` + +### CheckGroupMembershipResult \ [Api16] + - Value `Boolean?` + +### CheckNameAvailabilityRequest [Api20180301Preview] + - Name `String` + - Type `Type?` **{ProvidersMicrosoftManagementGroups}** + +### CheckNameAvailabilityResult [Api20180301Preview] + - Message `String` + - NameAvailable `Boolean?` + - Reason `Reason?` **{AlreadyExists, Invalid}** + +### ClassicAdministrator [Api20150701] + - EmailAddress `String` + - Id `String` + - Name `String` + - Role `String` + - Type `String` + +### ClassicAdministratorListResult [Api20150701] + - NextLink `String` + - Value `IClassicAdministrator[]` + +### ClassicAdministratorProperties [Api20150701] + - EmailAddress `String` + - Role `String` + +### ComponentsSchemasIdentityPropertiesUserassignedidentitiesAdditionalproperties [Api20180501] + - ClientId `String` + - PrincipalId `String` + +### CreateManagementGroupChildInfo [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### CreateManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### CreateManagementGroupProperties [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### CreateManagementGroupRequest [Api20180301Preview] + - Child `ICreateManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### CreateParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### DebugSetting [Api20180501] + - DetailLevel `String` + +### DenyAssignment [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - Id `String` + - IsSystemProtected `Boolean?` + - Name `String` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + - Type `String` + +### DenyAssignmentListResult [Api20180701Preview] + - NextLink `String` + - Value `IDenyAssignment[]` + +### DenyAssignmentPermission [Api20180701Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### DenyAssignmentProperties [Api20180701Preview] + - DenyAssignmentName `String` + - Description `String` + - DoNotApplyToChildScope `Boolean?` + - ExcludePrincipal `IPrincipal[]` + - IsSystemProtected `Boolean?` + - Permission `IDenyAssignmentPermission[]` + - Principal `IPrincipal[]` + - Scope `String` + +### Dependency [Api20180501] + - DependsOn `IBasicDependency[]` + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### Deployment [Api20180501] + - DebugSettingDetailLevel `String` + - Location `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentExportResult [Api20180501] + - Template `IDeploymentExportResultTemplate` + +### DeploymentExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Id `String` + - Location `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - Name `String` + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + - Type `String` + +### DeploymentListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentExtended[]` + +### DeploymentOperation [Api20180501] + - Id `String` + - OperationId `String` + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationProperties [Api20180501] + - ProvisioningState `String` + - RequestContent `IHttpMessageContent` + - ResponseContent `IHttpMessageContent` + - ServiceRequestId `String` + - StatusCode `String` + - StatusMessage `IDeploymentOperationPropertiesStatusMessage` + - TargetResourceId `String` + - TargetResourceName `String` + - TargetResourceType `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentOperationsListResult [Api20180501] + - NextLink `String` + - Value `IDeploymentOperation[]` + +### DeploymentProperties [Api20180501] + - DebugSettingDetailLevel `String` + - Mode `DeploymentMode` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Parameter `IDeploymentPropertiesParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Template `IDeploymentPropertiesTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + +### DeploymentPropertiesExtended [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DeploymentValidateResult [Api20180501] + - CorrelationId `String` + - DebugSettingDetailLevel `String` + - Dependency `IDependency[]` + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Mode `DeploymentMode?` **{Complete, Incremental}** + - OnErrorDeploymentName `String` + - OnErrorDeploymentProvisioningState `String` + - OnErrorDeploymentType `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + - Output `IDeploymentPropertiesExtendedOutputs` + - Parameter `IDeploymentPropertiesExtendedParameters` + - ParameterLinkContentVersion `String` + - ParameterLinkUri `String` + - Provider `IProvider[]` + - ProvisioningState `String` + - Template `IDeploymentPropertiesExtendedTemplate` + - TemplateLinkContentVersion `String` + - TemplateLinkUri `String` + - Timestamp `DateTime?` **{MinValue, MaxValue}** + +### DescendantInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - ParentId `String` + - Type `String` + +### DescendantInfoProperties [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### DescendantListResult [Api20180301Preview] + - NextLink `String` + - Value `IDescendantInfo[]` + +### DescendantParentGroupInfo [Api20180301Preview] + - Id `String` + +### DirectoryObject \ [Api16] + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - ObjectId `String` + - ObjectType `String` + +### DirectoryObjectListResult [Api16] + - OdataNextLink `String` + - Value `IDirectoryObject[]` + +### Domain \ [Api16] + - AuthenticationType `String` + - IsDefault `Boolean?` + - IsVerified `Boolean?` + - Name `String` + +### DomainListResult [Api16] + - Value `IDomain[]` + +### EntityInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - InheritedPermission `String` + - Name `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + - Type `String` + +### EntityInfoProperties [Api20180301Preview] + - DisplayName `String` + - InheritedPermission `String` + - NumberOfChild `Int32?` + - NumberOfChildGroup `Int32?` + - NumberOfDescendant `Int32?` + - ParentDisplayNameChain `String[]` + - ParentId `String` + - ParentNameChain `String[]` + - Permission `String` + - TenantId `String` + +### EntityListResult [Api20180301Preview] + - Count `Int32?` + - NextLink `String` + - Value `IEntityInfo[]` + +### EntityParentGroupInfo [Api20180301Preview] + - Id `String` + +### ErrorDetails [Api20180301Preview] + - Code `String` + - Detail `String` + - Message `String` + +### ErrorMessage [Api16] + - Message `String` + +### ErrorResponse [Api20160901Preview, Api20180301Preview] + - ErrorCode `String` + - ErrorDetail `String` + - ErrorMessage `String` + - HttpStatus `String` + +### ExportTemplateRequest [Api20180501] + - Option `String` + - Resource `String[]` + +### FeatureOperationsListResult [Api20151201] + - NextLink `String` + - Value `IFeatureResult[]` + +### FeatureProperties [Api20151201] + - State `String` + +### FeatureResult [Api20151201] + - Id `String` + - Name `String` + - State `String` + - Type `String` + +### GenericResource [Api20160901Preview, Api20180501] + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - IdentityUserAssignedIdentity `IIdentityUserAssignedIdentities ` + - Kind `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - PlanName `String` + - PlanProduct `String` + - PlanPromotionCode `String` + - PlanPublisher `String` + - PlanVersion `String` + - Property `IGenericResourceProperties` + - SkuCapacity `Int32?` + - SkuFamily `String` + - SkuModel `String` + - SkuName `String` + - SkuSize `String` + - SkuTier `String` + - Tag `IResourceTags ` + - Type `String` + +### GetObjectsParameters \ [Api16] + - IncludeDirectoryObjectReference `Boolean?` + - ObjectId `String[]` + - Type `String[]` + +### GraphError [Api16] + - ErrorMessageValueMessage `String` + - OdataErrorCode `String` + +### GroupAddMemberParameters \ [Api16] + - Url `String` + +### GroupCreateParameters \ [Api16] + - DisplayName `String` + - MailEnabled `Boolean` + - MailNickname `String` + - SecurityEnabled `Boolean` + +### GroupGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### GroupGetMemberGroupsResult [Api16] + - Value `String[]` + +### GroupListResult [Api16] + - OdataNextLink `String` + - Value `IAdGroup[]` + +### HttpMessage [Api20180501] + - Content `IHttpMessageContent` + +### Identity [Api20160901Preview, Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - UserAssignedIdentity `IIdentityUserAssignedIdentities ` + +### Identity1 [Api20180501] + - PrincipalId `String` + - TenantId `String` + - Type `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + +### InformationalUrl [Api16] + - Marketing `String` + - Privacy `String` + - Support `String` + - TermsOfService `String` + +### KeyCredential \ [Api16] + - CustomKeyIdentifier `String` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Type `String` + - Usage `String` + - Value `String` + +### KeyCredentialListResult [Api16] + - Value `IKeyCredential[]` + +### KeyCredentialsUpdateParameters [Api16] + - Value `IKeyCredential[]` + +### Location [Api20160601] + - DisplayName `String` + - Id `String` + - Latitude `String` + - Longitude `String` + - Name `String` + - SubscriptionId `String` + +### LocationListResult [Api20160601] + - Value `ILocation[]` + +### ManagementGroup [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - Id `String` + - Name `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + - Type `String` + +### ManagementGroupChildInfo [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DisplayName `String` + - Id `String` + - Name `String` + - Role `String[]` + - Type `String` + +### ManagementGroupDetails [Api20180301Preview] + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - UpdatedBy `String` + - UpdatedTime `DateTime?` **{MinValue, MaxValue}** + - Version `Single?` + +### ManagementGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - TenantId `String` + - Type `String` + +### ManagementGroupInfoProperties [Api20180301Preview] + - DisplayName `String` + - TenantId `String` + +### ManagementGroupListResult [Api20180301Preview] + - NextLink `String` + - Value `IManagementGroupInfo[]` + +### ManagementGroupProperties [Api20180301Preview] + - Child `IManagementGroupChildInfo[]` + - DetailUpdatedBy `String` + - DetailUpdatedTime `DateTime?` **{MinValue, MaxValue}** + - DetailVersion `Single?` + - DisplayName `String` + - ParentDisplayName `String` + - ParentId `String` + - ParentName `String` + - Role `String[]` + - TenantId `String` + +### ManagementLockListResult [Api20160901] + - NextLink `String` + - Value `IManagementLockObject[]` + +### ManagementLockObject [Api20160901] + - Id `String` + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Name `String` + - Note `String` + - Owner `IManagementLockOwner[]` + - Type `String` + +### ManagementLockOwner [Api20160901] + - ApplicationId `String` + +### ManagementLockProperties [Api20160901] + - Level `LockLevel` **{CanNotDelete, NotSpecified, ReadOnly}** + - Note `String` + - Owner `IManagementLockOwner[]` + +### OAuth2Permission [Api16] + - AdminConsentDescription `String` + - AdminConsentDisplayName `String` + - Id `String` + - IsEnabled `Boolean?` + - Type `String` + - UserConsentDescription `String` + - UserConsentDisplayName `String` + - Value `String` + +### OAuth2PermissionGrant [Api16] + - ClientId `String` + - ConsentType `ConsentType?` **{AllPrincipals, Principal}** + - ExpiryTime `String` + - ObjectId `String` + - OdataType `String` + - PrincipalId `String` + - ResourceId `String` + - Scope `String` + - StartTime `String` + +### OAuth2PermissionGrantListResult [Api16] + - OdataNextLink `String` + - Value `IOAuth2PermissionGrant[]` + +### OdataError [Api16] + - Code `String` + - ErrorMessageValueMessage `String` + +### OnErrorDeployment [Api20180501] + - DeploymentName `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### OnErrorDeploymentExtended [Api20180501] + - DeploymentName `String` + - ProvisioningState `String` + - Type `OnErrorDeploymentType?` **{LastSuccessful, SpecificDeployment}** + +### Operation [Api20151201, Api20180301Preview] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayResource `String` + - Name `String` + +### OperationDisplay [Api20151201] + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationDisplayProperties [Api20180301Preview] + - Description `String` + - Operation `String` + - Provider `String` + - Resource `String` + +### OperationListResult [Api20151201, Api20180301Preview] + - NextLink `String` + - Value `IOperation[]` + +### OperationResults [Api20180301Preview] + - Id `String` + - Name `String` + - ProvisioningState `String` + - Type `String` + +### OperationResultsProperties [Api20180301Preview] + - ProvisioningState `String` + +### OptionalClaim [Api16] + - AdditionalProperty `IOptionalClaimAdditionalProperties` + - Essential `Boolean?` + - Name `String` + - Source `String` + +### OptionalClaims [Api16] + - AccessToken `IOptionalClaim[]` + - IdToken `IOptionalClaim[]` + - SamlToken `IOptionalClaim[]` + +### ParametersLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### ParentGroupInfo [Api20180301Preview] + - DisplayName `String` + - Id `String` + - Name `String` + +### PasswordCredential \ [Api16] + - CustomKeyIdentifier `Byte[]` + - EndDate `DateTime?` **{MinValue, MaxValue}** + - KeyId `String` + - StartDate `DateTime?` **{MinValue, MaxValue}** + - Value `String` + +### PasswordCredentialListResult [Api16] + - Value `IPasswordCredential[]` + +### PasswordCredentialsUpdateParameters [Api16] + - Value `IPasswordCredential[]` + +### PasswordProfile \ [Api16] + - ForceChangePasswordNextLogin `Boolean?` + - Password `String` + +### PatchManagementGroupRequest [Api20180301Preview] + - DisplayName `String` + - ParentId `String` + +### Permission [Api20150701, Api201801Preview] + - Action `String[]` + - DataAction `String[]` + - NotAction `String[]` + - NotDataAction `String[]` + +### PermissionGetResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IPermission[]` + +### Plan [Api20160901Preview, Api20180501] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PlanPatchable [Api20160901Preview] + - Name `String` + - Product `String` + - PromotionCode `String` + - Publisher `String` + - Version `String` + +### PolicyAssignment [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - IdentityPrincipalId `String` + - IdentityTenantId `String` + - IdentityType `ResourceIdentityType?` **{None, SystemAssigned, SystemAssignedUserAssigned, UserAssigned}** + - Location `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - Name `String` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + - SkuName `String` + - SkuTier `String` + - Type `String` + +### PolicyAssignmentListResult [Api20151101, Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyAssignment[]` + +### PolicyAssignmentProperties [Api20151101, Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyAssignmentPropertiesMetadata` + - NotScope `String[]` + - Parameter `IPolicyAssignmentPropertiesParameters` + - PolicyDefinitionId `String` + - Scope `String` + +### PolicyDefinition [Api20161201, Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Name `String` + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Property `IPolicyDefinitionProperties` + - Type `String` + +### PolicyDefinitionListResult [Api20161201, Api20180501] + - NextLink `String` + - Value `IPolicyDefinition[]` + +### PolicyDefinitionProperties [Api20161201] + - Description `String` + - DisplayName `String` + - Metadata `IPolicyDefinitionPropertiesMetadata` + - Mode `PolicyMode?` **{All, Indexed, NotSpecified}** + - Parameter `IPolicyDefinitionPropertiesParameters` + - PolicyRule `IPolicyDefinitionPropertiesPolicyRule` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicyDefinitionReference [Api20180501] + - Parameter `IPolicyDefinitionReferenceParameters` + - PolicyDefinitionId `String` + +### PolicySetDefinition [Api20180501] + - Description `String` + - DisplayName `String` + - Id `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Name `String` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + - Type `String` + +### PolicySetDefinitionListResult [Api20180501] + - NextLink `String` + - Value `IPolicySetDefinition[]` + +### PolicySetDefinitionProperties [Api20180501] + - Description `String` + - DisplayName `String` + - Metadata `IPolicySetDefinitionPropertiesMetadata` + - Parameter `IPolicySetDefinitionPropertiesParameters` + - PolicyDefinition `IPolicyDefinitionReference[]` + - PolicyType `PolicyType?` **{BuiltIn, Custom, NotSpecified}** + +### PolicySku [Api20180501] + - Name `String` + - Tier `String` + +### PreAuthorizedApplication [Api16] + - AppId `String` + - Extension `IPreAuthorizedApplicationExtension[]` + - Permission `IPreAuthorizedApplicationPermission[]` + +### PreAuthorizedApplicationExtension [Api16] + - Condition `String[]` + +### PreAuthorizedApplicationPermission [Api16] + - AccessGrant `String[]` + - DirectAccessGrant `Boolean?` + +### Principal [Api20180701Preview] + - Id `String` + - Type `String` + +### Provider [Api20180501] + - Id `String` + - Namespace `String` + - RegistrationState `String` + - ResourceType `IProviderResourceType[]` + +### ProviderListResult [Api20180501] + - NextLink `String` + - Value `IProvider[]` + +### ProviderOperation [Api20150701, Api201801Preview] + - Description `String` + - DisplayName `String` + - IsDataAction `Boolean?` + - Name `String` + - Origin `String` + - Property `IProviderOperationProperties` + +### ProviderOperationsMetadata [Api20150701, Api201801Preview] + - DisplayName `String` + - Id `String` + - Name `String` + - Operation `IProviderOperation[]` + - ResourceType `IResourceType[]` + - Type `String` + +### ProviderOperationsMetadataListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IProviderOperationsMetadata[]` + +### ProviderResourceType [Api20180501] + - Alias `IAliasType[]` + - ApiVersion `String[]` + - Location `String[]` + - Property `IProviderResourceTypeProperties ` + - ResourceType `String` + +### RequiredResourceAccess \ [Api16] + - ResourceAccess `IResourceAccess[]` + - ResourceAppId `String` + +### Resource [Api20160901Preview] + - Id `String` + - Location `String` + - Name `String` + - Tag `IResourceTags ` + - Type `String` + +### ResourceAccess \ [Api16] + - Id `String` + - Type `String` + +### ResourceGroup [Api20180501] + - Id `String` + - Location `String` + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupTags ` + - Type `String` + +### ResourceGroupExportResult [Api20180501] + - ErrorCode `String` + - ErrorDetail `IResourceManagementErrorWithDetails[]` + - ErrorMessage `String` + - ErrorTarget `String` + - Template `IResourceGroupExportResultTemplate` + +### ResourceGroupListResult [Api20180501] + - NextLink `String` + - Value `IResourceGroup[]` + +### ResourceGroupPatchable [Api20180501] + - ManagedBy `String` + - Name `String` + - ProvisioningState `String` + - Tag `IResourceGroupPatchableTags ` + +### ResourceGroupProperties [Api20180501] + - ProvisioningState `String` + +### ResourceLink [Api20160901] + - Id `String` + - Name `String` + - Note `String` + - SourceId `String` + - TargetId `String` + - Type `IResourceLinkType` + +### ResourceLinkProperties [Api20160901] + - Note `String` + - SourceId `String` + - TargetId `String` + +### ResourceLinkResult [Api20160901] + - NextLink `String` + - Value `IResourceLink[]` + +### ResourceListResult [Api20180501] + - NextLink `String` + - Value `IGenericResource[]` + +### ResourceManagementErrorWithDetails [Api20180501] + - Code `String` + - Detail `IResourceManagementErrorWithDetails[]` + - Message `String` + - Target `String` + +### ResourceProviderOperationDefinition [Api20151101] + - DisplayDescription `String` + - DisplayOperation `String` + - DisplayProvider `String` + - DisplayPublisher `String` + - DisplayResource `String` + - Name `String` + +### ResourceProviderOperationDetailListResult [Api20151101] + - NextLink `String` + - Value `IResourceProviderOperationDefinition[]` + +### ResourceProviderOperationDisplayProperties [Api20151101] + - Description `String` + - Operation `String` + - Provider `String` + - Publisher `String` + - Resource `String` + +### ResourcesIdentity [Models] + - ApplianceDefinitionId `String` + - ApplianceDefinitionName `String` + - ApplianceId `String` + - ApplianceName `String` + - ApplicationDefinitionId `String` + - ApplicationDefinitionName `String` + - ApplicationId `String` + - ApplicationId1 `String` + - ApplicationName `String` + - ApplicationObjectId `String` + - DenyAssignmentId `String` + - DeploymentName `String` + - DomainName `String` + - FeatureName `String` + - GroupId `String` + - GroupObjectId `String` + - Id `String` + - LinkId `String` + - LockName `String` + - ManagementGroupId `String` + - MemberObjectId `String` + - ObjectId `String` + - OperationId `String` + - OwnerObjectId `String` + - ParentResourcePath `String` + - PolicyAssignmentId `String` + - PolicyAssignmentName `String` + - PolicyDefinitionName `String` + - PolicySetDefinitionName `String` + - ResourceGroupName `String` + - ResourceId `String` + - ResourceName `String` + - ResourceProviderNamespace `String` + - ResourceType `String` + - RoleAssignmentId `String` + - RoleAssignmentName `String` + - RoleDefinitionId `String` + - RoleId `String` + - Scope `String` + - SourceResourceGroupName `String` + - SubscriptionId `String` + - TagName `String` + - TagValue `String` + - TenantId `String` + - UpnOrObjectId `String` + +### ResourcesMoveInfo [Api20180501] + - Resource `String[]` + - TargetResourceGroup `String` + +### ResourceType [Api20150701, Api201801Preview] + - DisplayName `String` + - Name `String` + - Operation `IProviderOperation[]` + +### RoleAssignment [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - Id `String` + - Name `String` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + - Type `String` + +### RoleAssignmentCreateParameters [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentListResult [Api20150701, Api20180901Preview] + - NextLink `String` + - Value `IRoleAssignment[]` + +### RoleAssignmentProperties [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + +### RoleAssignmentPropertiesWithScope [Api20150701, Api20171001Preview, Api20180901Preview] + - CanDelegate `Boolean?` + - PrincipalId `String` + - PrincipalType `PrincipalType?` **{Application, DirectoryObjectOrGroup, DirectoryRoleTemplate, Everyone, ForeignGroup, Group, Msi, ServicePrincipal, Unknown, User}** + - RoleDefinitionId `String` + - Scope `String` + +### RoleDefinition [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Id `String` + - Name `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + - Type `String` + +### RoleDefinitionListResult [Api20150701, Api201801Preview] + - NextLink `String` + - Value `IRoleDefinition[]` + +### RoleDefinitionProperties [Api20150701, Api201801Preview] + - AssignableScope `String[]` + - Description `String` + - Permission `IPermission[]` + - RoleName `String` + - RoleType `String` + +### ServicePrincipal \ [Api16] + - AccountEnabled `Boolean?` + - AlternativeName `String[]` + - AppDisplayName `String` + - AppId `String` + - AppOwnerTenantId `String` + - AppRole `IAppRole[]` + - AppRoleAssignmentRequired `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - ErrorUrl `String` + - Homepage `String` + - KeyCredentials `IKeyCredential[]` + - LogoutUrl `String` + - Name `String[]` + - Oauth2Permission `IOAuth2Permission[]` + - ObjectId `String` + - ObjectType `String` + - PasswordCredentials `IPasswordCredential[]` + - PreferredTokenSigningKeyThumbprint `String` + - PublisherName `String` + - ReplyUrl `String[]` + - SamlMetadataUrl `String` + - Tag `String[]` + - Type `String` + +### ServicePrincipalBase [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalCreateParameters [Api16] + - AccountEnabled `Boolean?` + - AppId `String` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### ServicePrincipalListResult [Api16] + - OdataNextLink `String` + - Value `IServicePrincipal[]` + +### ServicePrincipalObjectResult [Api16] + - OdataMetadata `String` + - Value `String` + +### ServicePrincipalUpdateParameters [Api16] + - AccountEnabled `Boolean?` + - AppRoleAssignmentRequired `Boolean?` + - KeyCredentials `IKeyCredential[]` + - PasswordCredentials `IPasswordCredential[]` + - ServicePrincipalType `String` + - Tag `String[]` + +### SignInName \ [Api16] + - Type `String` + - Value `String` + +### Sku [Api20160901Preview, Api20180501] + - Capacity `Int32?` + - Family `String` + - Model `String` + - Name `String` + - Size `String` + - Tier `String` + +### Subscription [Api20160601] + - AuthorizationSource `String` + - DisplayName `String` + - Id `String` + - PolicyLocationPlacementId `String` + - PolicyQuotaId `String` + - PolicySpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + - State `SubscriptionState?` **{Deleted, Disabled, Enabled, PastDue, Warned}** + - SubscriptionId `String` + +### SubscriptionPolicies [Api20160601] + - LocationPlacementId `String` + - QuotaId `String` + - SpendingLimit `SpendingLimit?` **{CurrentPeriodOff, Off, On}** + +### TagCount [Api20180501] + - Type `String` + - Value `Int32?` + +### TagDetails [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagName `String` + - Value `ITagValue[]` + +### TagsListResult [Api20180501] + - NextLink `String` + - Value `ITagDetails[]` + +### TagValue [Api20180501] + - CountType `String` + - CountValue `Int32?` + - Id `String` + - TagValue1 `String` + +### TargetResource [Api20180501] + - Id `String` + - ResourceName `String` + - ResourceType `String` + +### TemplateLink [Api20180501] + - ContentVersion `String` + - Uri `String` + +### TenantBackfillStatusResult [Api20180301Preview] + - Status `Status?` **{Cancelled, Completed, Failed, NotStarted, NotStartedButGroupsExist, Started}** + - TenantId `String` + +### TenantIdDescription [Api20160601] + - Id `String` + - TenantId `String` + +### TenantListResult [Api20160601] + - NextLink `String` + - Value `ITenantIdDescription[]` + +### User \ [Api16] + - AccountEnabled `Boolean?` + - DeletionTimestamp `DateTime?` **{MinValue, MaxValue}** + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - ObjectId `String` + - ObjectType `String` + - PrincipalName `String` + - SignInName `ISignInName[]` + - Surname `String` + - Type `UserType?` **{Guest, Member}** + - UsageLocation `String` + +### UserBase \ [Api16] + - GivenName `String` + - ImmutableId `String` + - Surname `String` + - UsageLocation `String` + - UserType `UserType?` **{Guest, Member}** + +### UserCreateParameters \ [Api16] + - AccountEnabled `Boolean` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - Mail `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + +### UserGetMemberGroupsParameters \ [Api16] + - SecurityEnabledOnly `Boolean` + +### UserGetMemberGroupsResult [Api16] + - Value `String[]` + +### UserListResult [Api16] + - OdataNextLink `String` + - Value `IUser[]` + +### UserUpdateParameters \ [Api16] + - AccountEnabled `Boolean?` + - DisplayName `String` + - GivenName `String` + - ImmutableId `String` + - MailNickname `String` + - PasswordProfile `IPasswordProfile ` + - Surname `String` + - UsageLocation `String` + - UserPrincipalName `String` + - UserType `UserType?` **{Guest, Member}** + diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/README.md new file mode 100644 index 00000000000..937f07f8fec --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/resources/README.md @@ -0,0 +1,11 @@ +# Resources +This directory can contain any additional resources for module that are not required at runtime. This directory **does not** get packaged with the module. If you have assets for custom implementation, place them into the `..\custom` folder. + +## Info +- Modifiable: yes +- Generated: no +- Committed: yes +- Packaged: no + +## Purpose +Use this folder to put anything you want to keep around as part of the repository for the module, but is not something that is required for the module. For example, development files, packaged builds, or additional information. This is only intended to be used in repositories where the module's output directory is cleaned, but tangential resources for the module want to remain intact. \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/test/README.md b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/test/README.md new file mode 100644 index 00000000000..7c752b4c8c4 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/tools/Resources/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/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 new file mode 100644 index 00000000000..5319862d337 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Get-SubscriptionIdTestSafe.ps1 @@ -0,0 +1,7 @@ +param() +if ($env:AzPSAutorestTestPlaybackMode) { + $loadEnvPath = Join-Path $PSScriptRoot '..' 'test' 'loadEnv.ps1' + . ($loadEnvPath) + return $env.SubscriptionId +} +return (Get-AzContext).Subscription.Id \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Unprotect-SecureString.ps1 b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Unprotect-SecureString.ps1 new file mode 100644 index 00000000000..cb05b51a622 --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/target/utils/Unprotect-SecureString.ps1 @@ -0,0 +1,16 @@ +#This script converts securestring to plaintext + +param( + [Parameter(Mandatory, ValueFromPipeline)] + [System.Security.SecureString] + ${SecureString} +) + +$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString) +try { + $plaintext = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr) +} finally { + [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr) +} + +return $plaintext \ No newline at end of file diff --git a/tests-upgrade/tests-emitter/Qumulo.Storage.Management/tspconfig.yaml b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/tspconfig.yaml new file mode 100644 index 00000000000..754cc05ccdc --- /dev/null +++ b/tests-upgrade/tests-emitter/Qumulo.Storage.Management/tspconfig.yaml @@ -0,0 +1,78 @@ +parameters: + "service-dir": + default: "sdk/liftrqumulo" +output-dir: "{project-root}/" +emit: + - "@azure-tools/typespec-autorest" +options: + "@azure-tools/typespec-autorest": + use-read-only-status-schema: true + emitter-output-dir: "{project-root}/.." + azure-resource-provider-folder: "resource-manager" + emit-common-types-schema: "never" + # `arm-resource-flattening` is only used for back-compat for specs existed on July 2024. All new service spec should NOT use this flag + arm-resource-flattening: true + output-file: "{azure-resource-provider-folder}/{service-name}/{version-status}/{version}/Qumulo.Storage.json" + "@azure-tools/typespec-ts": + azureSdkForJs: true + isModularLibrary: true + generateMetadata: true + hierarchyClient: false + experimentalExtensibleEnums: true + enableOperationGroup: true + package-dir: "arm-qumulo" + flavor: "azure" + packageDetails: + name: "@azure/arm-qumulo" + "@azure-tools/typespec-python": + package-dir: "azure-mgmt-qumulo" + package-name: "{package-dir}" + flavor: "azure" + generate-test: true + generate-sample: true + "@azure-tools/typespec-powershell": + service-dir: "src" + package-dir: "Qumulo/Qumulo.Autorest" + clear-output-folder: true + azure: true + module-version: 0.1.0 + skip-model-cmdlets: false + help-link-prefix: https://learn.microsoft.com/powershell/module/ + metadata: + authors: Microsoft Corporation + owners: Microsoft Corporation + description: 'Microsoft Azure PowerShell: Qumulo cmdlets' + copyright: Microsoft Corporation. All rights reserved. + tags: Azure ResourceManager ARM PSModule Sphere + companyName: Microsoft Corporation + requireLicenseAcceptance: true + licenseUri: https://aka.ms/azps-license + projectUri: https://github.com/Azure/azure-powershell + prefix: 'Az' + subject-prefix: 'Qumulo' + service-name: Qumulo + module-name: "{prefix}.{service-name}" + namespace: "Microsoft.Azure.PowerShell.Cmdlets.{service-name}" + use-namespace-folders: false + # output-folder: "{output-dir}" + exclude-tableview-properties: + - Id + - Type + directive: + - where: + subject: Operation + hide: true + - where: + parameter-name: SubscriptionId + set: + default: + script: '(Get-AzContext).Subscription.Id' + - where: + variant: ^(Create|Update)(?!.*?Expanded|ViaJsonString|ViaJsonFilePath) + remove: true + - where: + verb: Set + hide: true +linter: + extends: + - "@azure-tools/typespec-azure-rulesets/resource-manager" diff --git a/tests-upgrade/tests-emitter/configuration.json b/tests-upgrade/tests-emitter/configuration.json index 273eb82ac7c..38deac1363a 100644 --- a/tests-upgrade/tests-emitter/configuration.json +++ b/tests-upgrade/tests-emitter/configuration.json @@ -1,16 +1,23 @@ { "description": "whiteTestList is the list we want to test and whiteTestListFull includes those that currently fail but we want to support", "whiteTestList": [ + "Astronomer.Astro.Management", + "AzureAI.Assets", + "CodeSigning.Management", + "Neon.Postgres.Management", + "Qumulo.Storage.Management", "Sphere.Management" ], "whiteTestListFull": [ + "Astronomer.Astro.Management", "AzureAI.Assets", "CodeSigning.Management", + "Neon.Postgres.Management", + "Qumulo.Storage.Management", "Sphere.Management" ], "blackTestList": [ - "AzureAI.Assets", - "CodeSigning.Management" + ], "ignoreFolder": [ "examples",